SpringBoot整合SpringDataJPA

2022-12-01 22:55:00 浏览数 (2)

SpringBoot整合SpringDataJPA

1. 添加依赖

2. 添加配置文件

代码语言:javascript复制
# jdbc 的相关信息
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
​
# 配置连接池信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
​
# 配置jpa的相关参数
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
​

3. 创建POJO

代码语言:javascript复制
package com.bobo.pojo;
​
import javax.persistence.*;
import java.io.Serializable;
​
@Table(name = "t_user")
@Entity
public class Users implements Serializable {
​
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer userId;
​
    @Column(name="user_name")
    private String usreName;
​
    @Column(name="real_name")
    private String realName;
​
    public Integer getUserId() {
        return userId;
    }
​
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
​
    public String getUsreName() {
        return usreName;
    }
​
    public void setUsreName(String usreName) {
        this.usreName = usreName;
    }
​
    public String getRealName() {
        return realName;
    }
​
    public void setRealName(String realName) {
        this.realName = realName;
    }
}
​

4. 创建接口

代码语言:javascript复制
package com.bobo.dao;
​
import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;
​
public interface UsersRepository extends JpaRepository<Users,Integer> {
}

5. 测试

代码语言:javascript复制
package com.bobo;
​
import com.bobo.dao.UsersRepository;
import com.bobo.pojo.Users;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
​
@SpringBootTest
class SpringdatajpaSpringbootApplicationTests {
​
    @Autowired
    private UsersRepository dao;
​
    @Test
    void contextLoads() {
        Users users = new Users();
        users.setUsreName("test1");
        users.setRealName("测试数据");
        dao.save(users);
    }
​
}
​

0 人点赞