SpringBoot整合SpringDataJPA
一沮协、添加Spring Data JPA的起步依賴
<!-- springBoot JPA的起步依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二囤锉、添加數(shù)據(jù)庫驅(qū)動坐標
<!-- MySQL連接驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
三偷溺、添加數(shù)據(jù)庫連接信息
在application.properties中配置數(shù)據(jù)庫和jpa的相關(guān)屬性
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
四哄孤、建表、創(chuàng)建實體類
在mysql中創(chuàng)建表胸私,并創(chuàng)建創(chuàng)建對應的實體類
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "user")
public class User implements Serializable {
// 主鍵
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
// 用戶名
@Column(name = "username")
private String username;
// 密碼
@Column(name = "password")
private String password;
// 姓名
@Column(name = "name")
private String name;
//此處省略setter和getter方法... ...
五毫捣、編寫dao層接口
繼承JpaRepository唠亚、JpaSpecificationExecutor接口担映,指定實體類以及主鍵泛型
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {}
六双饥、編寫Controller/Service進行開發(fā)
七蚯姆、補充
jdk9版本需要添加一個依賴
<!--jdk9需要導入如下坐標-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>