Spring Boot 可以看作一个粘贴器, 他可以粘贴n种技术. 关于更多整合: 参考github
Spring boot 整合持久层技术
JdbcTemplate & MyBatis
- 创建数据库及表
- 引入依赖
- 数据库配置
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字句 |
---|---|---|
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(?) |
jpa 也支持原生
SQL
, 在注解中加入nativeQuery= true
附: Druid
Druid连接池是阿里巴巴开源的数据库连接池项目.
Druid连接池为监控而生
, 内置强大的监控功能, 监控特性不影响性能. 功能强大, 能防SQL注入, 内置Logging能诊断Hack应用行为.
参考案例