spring boot jpa整合和使用讲解
1.pom.xml中添加jpa依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
2.application.yml中配置数据库连接和jpa的相关属性
- spring:
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://192.168.1.18/db_sell?charactorEncoding=utf-8&useSSL=false
- username: root
- password: 123456
- jpa:
- show-sql: true
如果用这中application.properties配置也差不多
- spring.jpa.show-sql = true
- #spring.jpa.hibernate.ddl-auto = update
- spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
- #spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultNamingStrategy
- spring.jpa.database = SQLSERVER
- spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
3.jpa的使用
spring data jpa 默认预先生成了一些基本的CURD的方法,例如:增、删、改等等
继承JpaRepository用的时候注入就可以直接使用了
spring data jpa方法命名规则
关键字 | 方法命名 | sql where字句 |
And | findByNameAndPwd | where name= ? and pwd =? |
Or | findByNameOrSex | where name= ? or sex=? |
Is,Equals | findById,findByIdEquals | where id= ? |
Between | findByIdBetween | where id between ? and ? |
LessThan | findByIdLessThan | where id < ? |
LessThanEquals | findByIdLessThanEquals | where id <= ? |
GreaterThan | findByIdGreaterThan | where id > ? |
GreaterThanEquals | findByIdGreaterThanEquals | where id > = ? |
After | findByIdAfter | where id > ? |
Before | findByIdBefore | where id < ? |
IsNull | findByNameIsNull | where name is null |
isNotNull,NotNull | findByNameNotNull | where name is not null |
Like | findByNameLike | where name like ? |
NotLike | findByNameNotLike | where name not like ? |
StartingWith |
findByNameStartingWith | where name like '?%' |
EndingWith | findByNameEndingWith | where name like '%?' |
Containing | findByNameContaining | where name like '%?%' |
OrderBy | findByIdOrderByXDesc | where id=? order by x desc |
Not | findByNameNot | where name <> ? |
In | findByIdIn(Collection<?> c) | where id in (?) |
NotIn | findByIdNotIn(Collection<?> c) | where id not in (?) |
True | findByAaaTue |
where aaa = true |
False | findByAaaFalse | where aaa = false |
IgnoreCase | findByNameIgnoreCase | where UPPER(name)=UPPER(?) |
自定义SQL查询
其实Spring data 觉大部分的SQL都可以根据方法名定义的方式来实现,但是由于某些原因我们想使用自定义的SQL来查询,
spring data也是完美支持的;在SQL的查询方法上面使用@Query
注解,如涉及到删除和修改在需要加上@Modifying
.
也可以根据需要添加 @Transactional
对事物的支持,查询超时的设置等
如果你是湖南的 欢迎加入 湖南人在深圳-Java群:557651502