Spring Boot 最佳实践(五)Spring Data JPA 操作 MySQL 8

 

一、Spring Data JPA 介绍

JPA(Java Persistence API)Java持久化API,是 Java 持久化的标准规范,Hibernate是持久化规范的技术实现,而Spring Data JPA是在 Hibernate 基础上封装的一款框架。

开发环境

  • Spring Boot 2.0.4
  • Spring Data JPA 2.0.4
  • MySQL 8.0.12
  • JDK 8
  • IDEA 2018.2
  • Windows 10

二、集成步骤

2.1 配置依赖

添加Spring Data JPA 和 MySQL Connector,配置pom.xml文件,代码如下:

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

更多JPA版本:upload/201809071538206782.gif"); background-position: left top; background-size: initial; background-repeat: no-repeat; background-attachment: initial; background-origin: initial; background-clip: initial; border: 2px solid rgb(239, 239, 239); padding: 6px 0px 6px 45px; margin: 0px auto; list-style-type: none; list-style-image: none; width: 4264.19px; color: rgb(102, 102, 102);">

spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

步骤二、在方法或类上标识事务@Transactional

示例代码:

@Transactional public void saveGroup(){     userRepository.save(user);     userRepository.save(user2); }

如果出现错误,就会进行事务回滚。

3.1.2 事务不生效的原因

3.1.2.1 确认数据库引擎

在application.properties配置数据库引擎为InnoDB:

spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

3.1.2.2 查看表的引擎必须为InnoDB

通过命令:

show table status from mytestdb;

修改表的引擎:

alter table table_name engine=innodb;

3.1.2.3 注意引入@Transactional的命名空间

@Transactional注解来自org.springframework.transaction.annotation包,而不是javax.transaction.

3.2 根据名称自动生成SQL

JPA支持根据简单的关键字自动生成Sql查询的方法,比如根据name和age的组合查询,代码如下:

public User findByNameAndAge(String name,int age);

使用关键字“And”即可,或者查询时间区间的:

public User findByStartDateBetween(Long startDate);

使用关键字“Between”即可。

更多内部支持的关键字,如下表:

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信