spring boot jpa整合和使用讲解

1.pom.xml中添加jpa依赖

  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-data-jpa</artifactId>  
  4. </dependency> 

2.application.yml中配置数据库连接和jpa的相关属性

  1. spring:  
  2.   datasource:  
  3.     driver-class-name: com.mysql.jdbc.Driver  
  4.     url: jdbc:mysql://192.168.1.18/db_sell?charactorEncoding=utf-8&useSSL=false  
  5.     username: root  
  6.     password: 123456  
  7.   jpa:  
  8.     show-sql: true 

     如果用这中application.properties配置也差不多

  1. spring.jpa.show-sql = true
  2. #spring.jpa.hibernate.ddl-auto = update
  3. spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
  4. #spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultNamingStrategy
  5. spring.jpa.database = SQLSERVER
  6. 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 对事物的支持,查询超时的设置等



如果你是湖南的 欢迎加入 湖南人在深圳-Java群:557651502

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值