版权声明:本文为博主原创文章,遵循
CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本文链接:
https://blog.csdn.net/lv_hang515888/article/details/804632271.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字句
AndfindByNameAndPwdwhere name= ? and pwd =?
OrfindByNameOrSexwhere name= ? or sex=?
Is,EqualsfindById,findByIdEqualswhere id= ?
BetweenfindByIdBetweenwhere id between ? and ?
LessThanfindByIdLessThanwhere id < ?
LessThanEqualsfindByIdLessThanEqualswhere id <= ?
GreaterThanfindByIdGreaterThanwhere id > ?
GreaterThanEqualsfindByIdGreaterThanEqualswhere id > = ?
AfterfindByIdAfterwhere id > ?
BeforefindByIdBeforewhere id < ?
IsNullfindByNameIsNullwhere name is null
isNotNull,NotNullfindByNameNotNullwhere name is not null
LikefindByNameLikewhere name like ?
NotLikefindByNameNotLikewhere name not like ?
StartingWith
findByNameStartingWithwhere name like '?%'
EndingWithfindByNameEndingWithwhere name like '%?'
ContainingfindByNameContainingwhere name like '%?%'
OrderByfindByIdOrderByXDescwhere id=? order by x desc
NotfindByNameNotwhere name <> ?
InfindByIdIn(Collection<?> c)where id in (?)
NotInfindByIdNotIn(Collection<?> c)where id not in (?)
True
findByAaaTue
where aaa = true
FalsefindByAaaFalsewhere aaa = false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)
自定义SQL查询
其实Spring data 觉大部分的SQL都可以根据方法名定义的方式来实现,但是由于某些原因我们想使用自定义的SQL来查询,
spring data也是完美支持的;在SQL的查询方法上面使用@Query注解,如涉及到删除和修改在需要加上@Modifying.
也可以根据需要添加 @Transactional 对事物的支持,查询超时的设置等