JPA(Java Persistence API)是一種對象關係映射的ORM框架,springboot-jpa能夠用簡單的配置來完成一些常規的數據庫crud操做
文檔:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/html
依賴java
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.14</version> <scope>provided</scope> </dependency> <!--開發工具--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
配置mysql
server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # mysql8推薦使用cj.jdbc, com.mysql.jdbc.Driver不推薦使用了 #數據庫鏈接池默認使用 tomcat-jdbc tomcat: max-idle: 10 min-idle: 1 initial-size: 1 jpa: database: MYSQL show-sql: true hibernate: ddl-auto: update
實體git
@Data @Entity(name = "user") public class User { @Id private int id; private String name; @Column(name = "phone_number", unique = true) private String phoneNumber; @Column(name = "create_time") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime = new Date(); }
daoweb
public interface UserRepository extends JpaRepository<User, Integer> { }
rest接口spring
@RestController @RequestMapping("/user") public class UserResource { @Autowired private UserRepository userRepository; @GetMapping("") public List<User> list(){ return userRepository.findAll(); } @PostMapping("") public User add(@RequestBody User user){ return userRepository.save(user); } }
啓動類sql
@SpringBootApplication public class MysqlApp { public static void main(String[] args) { SpringApplication.run(MysqlApp.class, args); } }
啓動app後,使用rest工具如postman來測試。數據庫
POST http://localhost:8080/user --- request body: { "name":"六六六", "phoneNumber":"15500000006" } --- response: { "id": 0, "name": "六六六", "phoneNumber": "15500000006", "createTime": "2018-12-02T01:34:41.382+0000" }
GET http://localhost:8080/user --- [ { "id": 1, "name": "張三", "phoneNumber": "15500000001", "createTime": "2018-12-01T13:04:53.000+0000" }, { "id": 2, "name": "李四", "phoneNumber": "15500000002", "createTime": "2018-12-01T13:04:56.000+0000" }, { "id": 3, "name": "王五", "phoneNumber": "15500000003", "createTime": "2018-12-01T13:05:02.000+0000" }, { "id": 5, "name": "六六六", "phoneNumber": "15500000006", "createTime": "2018-12-02T01:34:41.000+0000" } ]
關鍵字 | 舉例 | 對應JPQL |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection<Age> ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> ages) | … where x.age not in ?1 |
TRUE | findByActiveTrue() | … where x.active = true |
FALSE | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
id | name | age | available(是否禁用) | createTime |
---|---|---|---|---|
1 | 張三 | 28 | true | 2018-01-01 |
2 | 李四 | 22 | false | 2018-05-03 |
3 | 麗麗 | 18 | true | 2018-12-30 |
根據name查詢tomcat
//select * from user where name=?1 User findByName(String name);//等同findOneByName List<User> findByName(String name);//等同findAllByName
userRepository.findByName("張三");
1 | 張三 | 28 | true | 2018-01-01 |
---|
根據name和age查詢springboot
//select * from user where name=?1 and age=?2 User findByNameAndAge(String name, int age);
userRepository.findByNameAndAge("張三", 28);
1 | 張三 | 28 | true | 2018-01-01 |
---|
//select * from user where name=?1 or age=?2 User findByNameOrAge(String name, int age);
//select * from user where name in(?1) List<User> findByNameIn(List<String> nameList);
如查詢年齡大於20的
//select * from user where age>?2 List<User> findByAgeGreaterThan(int age);
userRepository.findByAgeGreaterThan(20);
id | name | age | available | createTime |
---|---|---|---|---|
1 | 張三 | 28 | true | 2018-01-01 |
2 | 李四 | 22 | false | 2018-05-03 |
如查詢禁用的用戶
//select * from user where available = 0 List<User> findByAvailableFalse();
userRepository.findByAvailableFalse();
2 | 李四 | 22 | false | 2018-05-03 |
---|
如按時間段查詢
//select * from user where createtime between ?1 and ?2 List<User> findByCreateTimeBetween(Date start, Date end);
userRepository.findByCreateTimeBetween(new Date("2018-05-01"), Date("2019-05-01")); //這裏new Date("2018-05-01")是舉例,實際中本身格式化爲java.util.Date類型便可
id | name | age | available | createTime |
---|---|---|---|---|
2 | 李四 | 22 | false | 2018-05-03 |
3 | 麗麗 | 18 | true | 2018-12-30 |
查詢前top頁的數據
//select * from user limit 10 List<User> findTop10(); //select * from user where available = 1 limit 10 List<User> findTop10ByAvailableIsTrue();
//select count(1) where age=?1 long countByAge(int age);
JPA也支持原生sql查詢,使用@Query
註解使用,如:
UserRepository:
//原生sql查詢 @Query(value = "select * from user where name=?1 and age > ?2", nativeQuery = true) List<User> queryBySQL(String name, int age);
接口:
@GetMapping("/sql") public List<User> sql(String name, int age){ return userRepository.queryBySQL(name, age); }
測試:
GET http://localhost:8080/user/sql?name=張三&age=10