JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
- SpringBoot使用SpringDataJPA完成CRUD操作. 数据的存储以及访问都是最为核心的关键部分,现在有很多企业采用主流的数据库,如关系型数据库:MySQL,Oracle,SQLServer。非关系型数据库:redis,mongodb等.
- Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。
1、导入相关依赖并配置文件
1 | xml复制代码<dependency> |
1 | yaml复制代码spring: |
2、JPA使用
步骤一:新建实体类并添加JPA注解
1 | java复制代码@Data |
步骤二:新建接口ArticleDao
1 | java复制代码/** |
步骤三:测试
1 | java复制代码@SpringBootTest |
3、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(?) |
4、JPQL语法生成
1 | java复制代码public interface StandardRepository extends JpaRepository<Standard, Long> { |
5、JPA URUD示例
modle:Article.java
1 | java复制代码@Data |
dao:ArticleDao.java
1 | java复制代码public interface ArticleDao extends JpaRepository<Article, Integer>, JpaSpecificationExecutor<Article>, Serializable { |
service:ArticleService.java
1 | java复制代码public interface ArticleService { |
serviceImpl:ArticleServiceImpl.java
1 | java复制代码@Service |
controller:ArticleController.java
1 | java复制代码@RestController |
6、JPA实现分页和模糊查询
modle:Article.java
1 | java复制代码@Data |
dao:ArticleDao.java
1 | java复制代码public interface ArticleDao extends JpaRepository<Article, Integer>, JpaSpecificationExecutor<Article>, Serializable { |
service:ArticleService.java
1 | java复制代码public interface ArticleService { |
serviceImpl:ArticleServiceImpl.java
1 | java复制代码@Service |
controller:ArticleController.java
1 | java复制代码@RestController |
本文转载自: 掘金