SpringBoot(25)之整合JPA

SpringBoot(25)之整合JPA

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

1、使用 Maven 构建 SpringBoot 项目,引入以下依赖:

image.png

2、配置数据源及 JPA:

# application.yml
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.202.135:3306/springboot_jpa
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    # JPA 默认使用 Hibernate 作为实现,所以可以使用 Hibernate 配置
    hibernate:
      # 更新或创建数据表
      ddl-auto: update
      # 输出执行的 sql
    show-sql: true

3、编写一个用于和数据库表映射的 JavaBean 即实体类,并配置好映射关系:

// com.springboot.data_jpa.bean.User
import javax.persistence.*;
import java.util.Date;

// 使用 JPA 注解配置映射关系
@Entity // 告诉 JPA 这是一个实体类
@Table(name = "user") // 指定与哪张数据表对应,如果省略默认表名为类名首字母小写
public class User {
    @Id // 标识该字段为主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "name",length = 40) // 指定与表中的哪个字段对应
    private String name;
    @Column // 如果省略默认列名为属性名
    private Integer gender;
    @Column
    private Date birthday;
    @Column
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

4、编写 Repository 接口来操作实体类对应的数据表:

// com.springboot.data_jpa.repository.UserRepository
import com.springboot.data_jpa.bean.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 第一个类型参数为要操作的实体类型
 * 第二个类型参数为实体对应的主键类型
 */
public interface UserRepository extends JpaRepository<User,Integer> {
}

5、测试:

import com.springboot.data_jpa.bean.User;
import com.springboot.data_jpa.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataJpaApplicationTests {

    @Autowired
    private UserRepository userRepository;
    @Test
    public void test() {
        System.out.println(userRepository);
        /*
        org.springframework.data.jpa.repository.support.SimpleJpaRepository@b022551
         */
    }

    @Test
    public void testAdd() throws ParseException {
        User user = new User();
        user.setName("赵六");
        user.setGender(1);
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1998-2-2"));
        user.setAddress("南京");
        User u = userRepository.save(user);
        System.out.println(u);
        /*
        Hibernate: insert into user (address, birthday, gender, name) values (?, ?, ?, ?)
        User{id=4, name='赵六'}
         */
    }

    @Test
    public void testGetAll(){
        List<User> all = userRepository.findAll();
        System.out.println(all);
        /*
        Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.birthday as birthday3_0_, user0_.gender as gender4_0_, user0_.name as name5_0_ from user user0_
        [User{id=1, name='张三'}, User{id=2, name='李四'}, User{id=3, name='王五'}, User{id=4, name='赵六'}]
         */
    }

    @Test
    public void testGetById(){
        User user = userRepository.findOne(1);
        System.out.println(user);
        /*
        Hibernate: select user0_.id as id1_0_0_, user0_.address as address2_0_0_, user0_.birthday as birthday3_0_0_, user0_.gender as gender4_0_0_, user0_.name as name5_0_0_ from user user0_ where user0_.id=?
        User{id=1, name='张三'}
         */
    }

    @Test
    public void testUpdate(){
        User user = userRepository.findOne(4);
        user.setGender(1);
        // 有主键时修改 否则保存
        userRepository.save(user);
        /*
        Hibernate: select user0_.id as id1_0_0_, user0_.address as address2_0_0_, user0_.birthday as birthday3_0_0_, user0_.gender as gender4_0_0_, user0_.name as name5_0_0_ from user user0_ where user0_.id=?
        Hibernate: update user set address=?, birthday=?, gender=?, name=? where id=?
         */
    }

    @Test
    public void testDelete(){
        userRepository.delete(4);
        /*
        Hibernate: select user0_.id as id1_0_0_, user0_.address as address2_0_0_, user0_.birthday as birthday3_0_0_, user0_.gender as gender4_0_0_, user0_.name as name5_0_0_ from user user0_ where user0_.id=?
        Hibernate: delete from user where id=?
         */
    }

}

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/springboot25.html

Buy me a cup of coffee ☕.