SpringBoot系列之Spring Data Jpa集成教程
Spring Data Jpa是屬於Spring Data的一個子項目,Spring data項目是一款集成了很多數據操作的項目,其下的子項目有如下圖所示:
官方也有提供了英文版的文檔,具體可以參考Spring data官方文檔
JPA是一個規范,並非具體的實現框架,而Spring Data JPA就是依賴於Hibernate JPA的實現
ok,接着通過例子的方式介紹Springboot集成Spring Data JPA的方法,進行實驗,要先創建一個Initializer工程,如圖:
新建項目后,會自動加上如下配置,,如果你的mysql服務器是5.7版本的,建議指定mysql-connector-java版本,Druid也需要自己加上,pom配置參考:
<properties>
<java.version>1.8</java.version>
<druid.version>1.1.2</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
新建數據庫和數據表:
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `springboot`;
/*Table structure for table `sys_user` */
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`userId` int(10) NOT NULL,
`username` varchar(20) NOT NULL,
`sex` char(10) DEFAULT NULL,
`password` varchar(10) DEFAULT NULL,
PRIMARY KEY (`userId`),
UNIQUE KEY `idx_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `sys_user` */
insert into `sys_user`(`userId`,`username`,`sex`,`password`) values (1,'admin','man','11');
新建一個bean類,代碼:
package com.example.springboot.jpa.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
@Entity
@Table(name = "sys_user")
//Springboot2.2.1集成的Spring data jpa比較新,需要加上如下配置
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class User{
@Id //主鍵
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主鍵
private Integer userId;
@Column(name = "username",length = 20) //這是和數據表對應的一個列
private String username;
@Column
private String sex;
@Column
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
實現JpaRepository接口,當然Spring data jpa還提供了很多接口,具體可以參考我之前博客:JPA系列之Spring Data JPA系列之入門教程,本博客只介紹在Springboot集成spring data jpa,具體使用還是需要看我之前博客,才可以再來學習本文
package com.example.springboot.jpa.repository;
import com.example.springboot.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> {
}
不寫Service類,直接寫個controller類進行測試
package com.example.springboot.jpa.controller;
import com.example.springboot.jpa.entity.User;
import com.example.springboot.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/user/{userId}")
public User getUser(@PathVariable("userId") Integer userId){
User user = userRepository.getOne(userId);
return user;
}
@GetMapping("/user")
public User insertUser(User user){
User save = userRepository.save(user);
return save;
}
}
application.yml配置,當然還要配置數據庫JDBC和連接池,具體參考我的博客:SpringBoot系列之集成Druid配置數據源監控,yaml不熟悉可以,參考我之前博客:SpringBoot系列之YAML配置用法學習筆記
spring:
jpa:
hibernate:
# 更新或者創建數據表結構
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
# 控制台顯示SQL
show-sql: true
啟動Postman來調試接口,測試通過:
代碼例子下載:github下載鏈接