Spring Boot—15SpringJPA
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency>
application.properties
# server.address=0.0.0.0 server.port=8080 server.servlet.context-path=/test
server.session.timeout=300 server.error.path=/error # Tomcat的访问日志,便于进行用户访问日志分析 server.tomcat.accesslog.enabled=true server.tomcat.accesslog.buffered=true server.tomcat.accesslog.directory=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/logs # JSON解析的配置 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
# spring.thymeleaf.cache=true spring.thymeleaf.enabled=true # 文件上传配置 file.upload.path=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/fileUpLoad
spring.servlet.multipart.enabled=true spring.servlet.multipart.file-size-threshold=0 spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/temp spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB spring.servlet.multipart.resolve-lazily=false spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# MySQL新的连接字符串(加了时区)
spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.one.username=root spring.datasource.druid.one.password=gis
# MySQL新的驱动 spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver ##Druid spring.datasource.druid.one.initial-size=2 spring.datasource.druid.one.max-active=5 spring.datasource.druid.one.min-idle=1 spring.datasource.druid.one.max-wait=60000 spring.datasource.druid.one.pool-prepared-statements=true spring.datasource.druid.one.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.one.validation-query-timeout=60000 spring.datasource.druid.one.test-on-borrow=false spring.datasource.druid.one.test-on-return=false spring.datasource.druid.one.test-while-idle=true spring.datasource.druid.one.time-between-eviction-runs-millis=60000 spring.datasource.druid.one.min-evictable-idle-time-millis=100000 #spring.datasource.druid.one.max-evictable-idle-time-millis= spring.datasource.druid.one.filters=stat,wall,log spring.datasource.druid.one.logSlowSql=true
数据库连接池的配置
package com.smartmap.sample.test.conf; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; @Configuration public class DataSourceConfiguration { private final Log logger = LogFactory.getLog(DataSourceConfiguration.class); @Primary @Bean @ConfigurationProperties("spring.datasource.druid.one") # 这样配置可以支持后面的多数据源的情况
public DataSource getDataSourceConfiguration() { return DruidDataSourceBuilder.create().build(); } }
强大的JpaRepository
package com.smartmap.sample.test.dao; import java.util.Date; import java.util.List; import java.util.Set; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import com.smartmap.sample.test.entity.User; public interface UserRepository extends JpaRepository<User, Long> { // 基于Spring的方法名字查询 public User findByName(String name); public List<User> findByCreateTimeGreaterThan(Date createTime); // JPQL 查询 @Query(value="select u from user u where u.name=?1 and u.department.id=?2", nativeQuery=true) public User findUser(String name, Long departmentId); // JPQA + 命名 @Query(value="select u from user u where u.name=:name and u.department.id=:departmentId", nativeQuery=true) public User findUser2(String name, Long departmentId); // SQL 查询 @Query(value="select id, name, create_time, department_id from user where name=:name and department_id=:departmentId", nativeQuery=true) public User findUserNativeQuery2(String name, Long departmentId); // SQL + 命名 @Query(value="select department_id, count(*) count from user group by department_id", nativeQuery= true) public List<Object[]> queryUserCount(); // 分页配合使用 @Query(value="select u from user u where u.department.id=?1", nativeQuery=true) public Page<User> queryUsers(Long departmentId, Pageable page); // 修改 @Modifying @Query("update User u set u.name=?1 where u.id=?2") public int updateName(String name, Long id); }
实体User
package com.smartmap.sample.test.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String name; @JsonBackReference // 防止相互引用,出现无限引用递归 @ManyToOne @JoinColumn(name = "department_id") private Department department; @Column(name = "create_time") private Date createTime; public User() { } public User(Long id, String name, Department department, Date createTime) { super(); this.id = id; this.name = name; this.department = department; this.createTime = createTime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Long getDepartmentId() { return this.department == null ? null : this.department.getId(); } public void setDepartmentId(Long departmentId) { if (this.department != null) { this.department.setId(departmentId); } } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
实体Department
package com.smartmap.sample.test.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonManagedReference; @Entity public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String name; @JsonManagedReference // 防止相互引用,出现无限引用递归 @OneToMany(mappedBy = "department") private Set<User> users = new HashSet<User>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
Serivce类
package com.smartmap.sample.test.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.smartmap.sample.test.dao.UserRepository; import com.smartmap.sample.test.entity.User; import com.smartmap.sample.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; public Long addUser(User user) { userRepository.save(user); Long id = user.getId(); user.setName(user.getName() + "-" + "1"); userRepository.save(user); return id; } public List<User> getUsersSorted() { Sort sort = Sort.by(Order.asc("id")); return userRepository.findAll(sort); } public List<User> getAllUsers(int page, int size){ Sort sort = Sort.by(Order.asc("id")); PageRequest pageRequest = PageRequest.of(page, size, sort); Page<User> pageUser = userRepository.findAll(pageRequest); int totalPage = pageUser.getTotalPages(); long count = pageUser.getTotalElements(); return pageUser.getContent(); } @Override public List<User> allUser() { /* * List<User> userList = new LinkedList<User>(); userList.add(new User("123", * "root")); */ return userRepository.findAll(); } @Override public User getUserById(Long userId) { /* return new User("123", "root"); */ return userRepository.findById(userId).orElse(null); } @Transactional @Override public User save(User user) { /* return new User("123", "root"); */ return userRepository.save(user); } @Override public int delete(Long userId) { /* return 1; */ userRepository.deleteById(userId); return 1; } }
RestController类
package com.smartmap.sample.test.controller.rest; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.smartmap.sample.test.entity.User; import com.smartmap.sample.test.service.UserService; @RestController @RequestMapping("/api/v1.1/system/user") public class UserRestController { private final Log logger = LogFactory.getLog(UserRestController.class); @Autowired UserService userService; /** * 查询所有用户 * * curl -XGET 'http://127.0.0.1:8080/api/v1.1/system/user/' * * @return */ @GetMapping("/") public List<User> getAllUsers() { return userService.allUser(); } /** * 根据Id查询用户 * * curl -XGET 'http://127.0.0.1:8080/api/v1.1/system/user/123' * * @param userId * @return */ @GetMapping("/{userId}") public User getUserById(@PathVariable("userId") Long userId) { return userService.getUserById(userId); } /** * 翻页查询用户 * * curl -XGET * 'http://127.0.0.1:8080/api/v1.1/system/user/query?offset=123&limit=456&sortBy=789&sortOrder=456' * * @param offset * @param limit * @param sortBy * @param sortOrder * @return */ @GetMapping("/query") public List<User> queryUserById(@RequestParam("offset") int offset, @RequestParam("limit") int limit, @RequestParam("sortBy") int sortBy, @RequestParam("sortOrder") int sortOrder) { logger.info(String.valueOf(offset)); logger.info(String.valueOf(limit)); logger.info(String.valueOf(sortBy)); logger.info(String.valueOf(sortOrder)); return userService.allUser(); } /** * 添加用户 * * curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/user/' * -H'Content-type:application/json;charset=UTF-8' -d ' { "name":"123", * "createTime":"2017-01-01 00:00:00", "departmentId":"9" }' * * @param user * @return */ @PostMapping("/") public User addUse(@RequestBody User user) { System.out.println(user.getName()); return userService.save(user); } /** * 更新用户 * * curl -XPUT 'http://127.0.0.1:8080/api/v1.1/system/user/' * -H'Content-type:application/json;charset=UTF-8' -d ' { "id": "123", * "name":"123" } ' * * @param user * @return */ @PutMapping("/") public User updateUse(@RequestBody User user) { return userService.save(user); } /** * 删除用户 * * curl -XDELETE 'http://127.0.0.1:8080/api/v1.1/system/user/123' * * @param userId * @return */ @DeleteMapping("/{userId}") public String deleteUser(@PathVariable("userId") Long userId) { if (userService.delete(userId) > 0) { return "{success:true, message:'delete success'}"; } else { return "{success:false, message:'delete fail'}"; } } }