SpringBoot整合SpringData Jpa

Posted Coreqi

tags:

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

(1)、添加依赖

1         <dependency>
2             <groupId>org.springframework.boot</groupId>
3             <artifactId>spring-boot-starter-data-jpa</artifactId>
4         </dependency>

(2)、编写实体类

 1 package cn.coreqi.entities;
 2 
 3 import javax.persistence.*;
 4 
 5 @Entity
 6 @Table(name = "users")
 7 public class User {
 8     @Id //标识当前类主键
 9     @GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
10     private Integer Id;
11     @Column(name = "UserName")
12     private String UserName;
13     @Column(name = "PassWord")
14     private String PassWord;
15     @Column(name = "Enabled")
16     private Integer Enabled;
17 
18     public User(String userName, String passWord, Integer enabled) {
19         UserName = userName;
20         PassWord = passWord;
21         Enabled = enabled;
22     }
23 
24     public Integer getId() {
25         return Id;
26     }
27 
28     public void setId(Integer id) {
29         Id = id;
30     }
31 
32     public String getUserName() {
33         return UserName;
34     }
35 
36     public void setUserName(String userName) {
37         UserName = userName;
38     }
39 
40     public String getPassWord() {
41         return PassWord;
42     }
43 
44     public void setPassWord(String passWord) {
45         PassWord = passWord;
46     }
47 
48     public Integer getEnabled() {
49         return Enabled;
50     }
51 
52     public void setEnabled(Integer enabled) {
53         Enabled = enabled;
54     }
55 
56     public User() {
57     }
58 }

(3)、配置Jpa

1 spring.datasource.username=root
2 spring.datasource.password=123456
3 spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC
4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
5 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
6 
7 spring.jpa.show-sql=true
8 spring.jpa.hibernate.ddl-auto=update

(4)、编写一个Dao接口来操作实体类对应的数据表(Repository)

 1 package cn.coreqi.dao;
 2 
 3 import cn.coreqi.entities.User;
 4 import org.springframework.data.jpa.repository.JpaRepository;
 5 import org.springframework.stereotype.Repository;
 6 
 7 /**
 8  * 通过继承JpaRepository来完成对数据库的操作
 9  * 第一个泛型为实体类名称
10  * 第二个泛型为实体类主键类型
11  */
12 @Repository
13 public interface UserRepository extends JpaRepository<User,Integer> {
14 }

 

以上是关于SpringBoot整合SpringData Jpa的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot整合JDBC

SpringBoot整合SpringData JPA

SpringBoot整合SpringData Jpa

SpringBoot07:整合JDBC

SpringBoot07:整合JDBC

SpringBoot--整合JDBC