Spring Boot (7) 整合持久层

Spring Boot (7) 整合持久层

Scroll Down

Spring Boot 可以看作一个粘贴器, 他可以粘贴n种技术. 关于更多整合: 参考github

Spring boot 整合持久层技术

JdbcTemplate & MyBatis

  1. 创建数据库及表
  2. 引入依赖
  3. 数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql:xxx:3306/xxx
spring.datasource.username=root
spring.datasource.password=xxx

Spring Data Jpa

application.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql:xxx:3306/xxx
spring.datasource.username=root
spring.datasource.password=xxx
spring.jpa.show-sql=true # 打印SQL
spring.jpa.hibernate.ddl-auto=update # 更新数据库表
spring.jpa.properties.hibernate.dialect=org.hibernate.dialec.MySQL57Dialect # 使用数据库方言

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 ?
StartingWithfindByNameStartingWithwhere 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 (?)
TruefindByAaaTuewhere aaa = true
FalsefindByAaaFalsewhere aaa = false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)

jpa 也支持原生SQL, 在注解中加入 nativeQuery= true

附: Druid

Druid连接池是阿里巴巴开源的数据库连接池项目. Druid连接池为监控而生, 内置强大的监控功能, 监控特性不影响性能. 功能强大, 能防SQL注入, 内置Logging能诊断Hack应用行为.

参考案例

支付宝 微信