SpringBoot系列:四SpringBoot集成JPA

Posted tassdar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot系列:四SpringBoot集成JPA相关的知识,希望对你有一定的参考价值。

首先要明白的是JPA不是产品,它是一个规范。

Jpa (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范。它为 Java 开发人员提供了一种对象/关联映射工具来管理 Java 应用中的关系数据。

它的出现主要是为了简化现有的持久化开发工作和整合 ORM 技术,结束现在 Hibernate,TopLink,JDO 等 ORM 框架各自为营的局面

在pom.xml中添加引用:jpa和mysql

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>


在配置文件中添加数据库链接配置
链接字符串要指定时区和编码格式不然会导致中文乱码和报错

技术图片

 

 

 

 

 

然后声明一个实体类,添加@Table注解制定表名,@Entity表明它是一个实体类Bean

@Id标明主键,@GeneratedValue标明主键类型,下图是mysql自增主键的例子

@Column指定映射的数据库列名,同名的话可以不写

技术图片

 

 

 

创建一个接口继承JpaRepository,然后我们就可以使用框架为我们封装好的CURD了 

技术图片

 

技术图片

 

 调用接口看一下返回效果

技术图片

 

 剩下的删除修改就不贴了都是一样的。

接下来是JPA的查询,JPA会根据方法的名字来生成对应的查询

技术图片

 

 到控制器层试一下

技术图片

 

 调用一下接口,完美返回

技术图片

 

删除跟新什么的都是这个套路,下面是一张对照表

KeywordSampleJPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

 

 

 

 接下来是JPA的分页,JPA中自带了分页可以让我们直接使用

 

 技术图片

 

调用接口返回

技术图片

 

 开箱即用

下一章,我们讲集成Mybaits

 

以上是关于SpringBoot系列:四SpringBoot集成JPA的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot系列四:SpringBoot开发(改变环境属性读取资源文件Bean 配置模版渲染profile 配置)

Springboot系列 集成接口文档swagger,使用,测试

Springboot系列 集成接口文档swagger,使用,测试

SpringBoot系列优雅的处理统一异常处理与统一结果返回

spring boot 学习笔记

Springboot系列web静态资源配置详解