1. Controller(EventController.java)
@RestController
@RequestMapping("/Event")
public class EventController {// 案件信息@AutowiredEventRepository eventRepository;// 添加、编辑@PostMapping("/addEvent")public ResponseObject addEvent(@RequestBody Event event) {eventRepository.save(event);return ResponseObject.ok("添加成功");}// 删除@PostMapping("/delEvent")public ResponseObject delEvent(@RequestBody Map<String,String> Map) {eventRepository.deleteById(Map.get("id"));return ResponseObject.ok("删除成功");}// 通过id查询@PostMapping("/getEventById")public ResponseObject getEventById(@RequestBody Map<String,String> Map) {if (Map.get("id") == null || Map.get("id") == "") {return ResponseObject.error("id为空!");}Optional<Event> event = eventRepository.findById(Map.get("id"));return new ResponseObject(200, "查询成功!", event);}// 查询全部@PostMapping("/getEventList")public ResponseObject getEventList(@RequestBody Map<String,String> Map) {Page<Event> pagePage = eventRepository.findAll(PageRequest.of(Integer.parseInt(Map.get("page")) - 1, Integer.parseInt(Map.get("limit"))));List<Event> list = pagePage.getContent();Map<String, Object> map = new HashMap<>();map.put("total", list.size());map.put("rows", list);return new ResponseObject(200, "查询成功", map);}
}
条件查询
// 查询条件
Specification<Event> specification = (root, query, builder) ->query.where(builder.equal(root.get("id"), item.getId())).getRestriction();// 查询
List<Event> list = eventRepository.findAll(specification);
2. 实体类(Event.java)
这里使用了lombok插件,自动省略了get、set方法。
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
@Data
@Entity
@Table(name = "database")
public class Event {@Idprivate String id;// 联系电话private String tel;// 姓名private String name;}
3. Repository(EventRepository.java)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
public interface EventRepository extends JpaSpecificationExecutor<Event>,JpaRepository<Event,String> {}
4. 配置数据库(Application.properties)
### web
server.port=8080### resources
spring.resources.static-locations=classpath:/static/# 配置SQLServer数据库连接
spring.datasource.url = jdbc:sqlserver://localhost:1433;DatabaseName=Database
spring.datasource.username = ***
spring.datasource.password = ***
spring.datasource.driver-class-name = com.microsoft.sqlserver.jdbc.SQLServerDriver# 配置JPA
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl