日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

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

發(fā)布時間:2025/3/11 数据库 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot 最佳实践(五)Spring Data JPA 操作 MySQL 8 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

## 一、Spring Data JPA 介紹

JPA(Java Persistence API)Java持久化API,是 Java 持久化的標準規(guī)范,Hibernate是持久化規(guī)范的技術實現(xiàn),而Spring Data JPA是在 Hibernate 基礎上封裝的一款框架。

開發(fā)環(huán)境

  • 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版本:http://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa

更多Mysql版本:http://mvnrepository.com/artifact/mysql/mysql-connector-java

2.2 application.properties 設置配置文件

## 數(shù)據(jù)源配置 spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.jpa.hibernate.ddl-auto=update spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql=true
  • hbm2ddl.auto:自動創(chuàng)建|更新|驗證數(shù)據(jù)庫表結構
  • dialect:設置數(shù)據(jù)庫引擎為InnoDB
  • show-sql:打印sql語句,方便調試

hbm2ddl.auto有四個屬性:

  • create:每次加載 hibernate 時都會刪除上一次的生成的表,然后根據(jù)你的 model 類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執(zhí)行,這就是導致數(shù)據(jù)庫表數(shù)據(jù)丟失的一個重要原因。[刪除-創(chuàng)建-操作]

  • create-drop :每次加載 hibernate 時根據(jù) model 類生成表,但是 sessionFactory 一關閉,表就自動刪除。[刪除-創(chuàng)建-操作-再刪除]

  • update:最常用的屬性,第一次加載 hibernate 時根據(jù) model 類會自動建立起表的結構(前提是先建立好數(shù)據(jù)庫),以后加載 hibernate 時根據(jù) model 類自動更新表結構,即使表結構改變了,但表中的行仍然存在,不會刪除以前的行。要注意的是當部署到服務器后,表結構是不會被馬上建立起來的,是要等應用第一次運行起來后才會。[沒表-創(chuàng)建-操作 | 有表-更新沒有的屬性列-操作]

  • validate:每次加載 hibernate 時,驗證創(chuàng)建數(shù)據(jù)庫表結構,只會和數(shù)據(jù)庫中的表進行比較,不會創(chuàng)建新表,但是會插入新值。[啟動驗證表結構,驗證不成功,項目啟動失敗]

2.3 增加實體類(Entity)

@Entity public class User implements Serializable {@Id@GeneratedValueprivate Long id;@Column(name = "name", nullable = false)private String name;@Column(nullable = false)private int age;@Column(nullable = false)private String pwd;public User(){}public User(String name, int age, String pwd) {this.name = name;this.age = age;this.pwd = pwd;}//...忽略set、get方法 }
  • @GeneratedValue 自動生成id
  • @Column 設置列屬性(name=”數(shù)據(jù)庫列名”)
  • @Transient 不會映射到數(shù)據(jù)庫

2.4 創(chuàng)建 Repository 接口構建業(yè)務方法

public interface UserRepository extends JpaRepository<User,Long> {public User findByName(String name); }

繼承JpaRepository之后就繼承了:

  • Repository.save(user); // 插入或保存
  • Repository.saveFlush(user); // 保存并刷新
  • Repository.exists(1) // 主鍵查詢是否存在
  • Repository.findOne(1); // 主鍵查詢單條
  • Repository.delete(1); // 主鍵刪除
  • Repository.findByUsername(“stone”); // 查詢單條
  • Repository.findAll(pageable); // 帶排序和分頁的查詢列表
  • Repository.saveState(1, 0); // 更新單個字段

這些方法,可以不寫一行代碼就可以實現(xiàn)對一個表的操作,當然你也可以擴展一些自己的方法,只需要在UserRepository里面添加方法即可。

2.5 添加、查詢數(shù)據(jù)庫

@Controller @RequestMapping("/") public class UserController {@Autowiredprivate UserRepository userRepository;@RequestMapping("/")public ModelAndView index() {userRepository.save(new User("老王",18,"123456"));ModelAndView modelAndView = new ModelAndView("/index");modelAndView.addObject("dataSize", userRepository.findAll().size());return modelAndView;} }

到現(xiàn)在為止,集成 Spring Data JPA 已經(jīng)全部完成了,啟動調試,查看運行效果吧。

三、高級使用

本節(jié)高級使用將會涉及的知識點如下:

  • 事務實現(xiàn)
  • 根據(jù)名稱自動生成SQL
  • 自定義Sql語句查詢

3.1 事務實現(xiàn)

3.1.1 Spring事務實現(xiàn)步驟

實現(xiàn)事務,只需要兩步即可:

步驟一、在application.properties配置數(shù)據(jù)庫引擎為InnoDB:

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

步驟二、在方法或類上標識事務@Transactional

示例代碼:

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

如果出現(xiàn)錯誤,就會進行事務回滾。

3.1.2 事務不生效的原因

3.1.2.1 確認數(shù)據(jù)庫引擎

在application.properties配置數(shù)據(jù)庫引擎為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 根據(jù)名稱自動生成SQL

JPA支持根據(jù)簡單的關鍵字自動生成Sql查詢的方法,比如根據(jù)name和age的組合查詢,代碼如下:

public User findByNameAndAge(String name,int age);

使用關鍵字“And”即可,或者查詢時間區(qū)間的:

public User findByStartDateBetween(Long startDate);

使用關鍵字“Between”即可。

更多內部支持的關鍵字,如下表:

KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstname,findByFirstnameIs… where x.firstname = ?1
BetweenfindByStartDateBetween… where x.startDate between ?1 and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age <= ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1(parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1(parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1(parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection ages)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)

官方文檔:https://docs.spring.io/spring-data/jpa/docs/2.0.9.RELEASE/reference/html/#jpa.repositories

3.3 自定義Sql語句查詢

對于用戶自己編寫sql,Spring Boot JPA也有很好的支持,只需要添加@Query(sql)即可。

示例代碼:

@Transactional @Modifying @Query("update User set name=?1 where id=?2") public int modifyName(String name,Long id);

注意:在執(zhí)行修改和刪除的時候必須添加@Modifying注解,ORM才知道要執(zhí)行寫操作,update/delete query 的時候,也必須需要加上@Transactional(事務)才能正常操作。

四、常見錯誤

在 Spring Data JPA 的使用當中,可能會遇到如下的一些錯誤。

1.No default constructor for entity

實體類Entity沒有空參數(shù)的默認構造函數(shù),新增即可解決。

2.java.sql.SQLException: Access denied for user ”@’172.17.0.1’ (using password: NO)

啟動項目報錯,用戶名和密碼配置的key有誤,MySQL8的用戶名和密碼配置和之前的不一樣,MySQL 8 正確的用戶名密碼配置如下:

spring.datasource.username=root spring.datasource.password=123456 # 以下為配置老數(shù)據(jù)庫驅動配置 #spring.datasource.data-username=root #spring.datasource.data-password=123456

3.Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver

MySQL 8 的spring.datasource.driver-class-name配置需要改為“com.mysql.cj.jdbc.Driver”而不是“com.mysql.jdbc.Driver”,正確配置如下:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

總結

以上是生活随笔為你收集整理的Spring Boot 最佳实践(五)Spring Data JPA 操作 MySQL 8的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。