首页 > 编程语言 > SpringBoot JPA使用配置过程详解
2020
09-28

SpringBoot JPA使用配置过程详解

JPA是什么? JPA(Java Persistence API)是Sun官方提出的Java持久化规范. 为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据. 它的出现是为了简化现有的持久化开发工作和整合ORM技术. 结束各个ORM框架各自为营的局面.
JPA 其实是一种规范,它的实现中比较出名的是 Hibernate 框架;

1、pom 引入依赖:

<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>
      <scope>runtime</scope>
      <version>5.1.18</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.10</version>
    </dependency>

2、添加配置文件

#数据库连接信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=521hui
spring.datasource.url=jdbc:mysql://localhost:3306/test
#JPA设置
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.database-platform=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

3、编写 bean

@Entity(name = "t_book")
public class Book {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;
  private String name;
  private String author;

  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 String getAuthor() {
    return author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

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

4、编写 接口

public interface BookDao extends JpaRepository<Book,Integer> {
}

5、启动程序,数据库创建表

6、进行 CRUD 测试

@Autowired
  BookDao bookDao;
  @Test
  void testInsert() {
    Book book = new Book();
    book.setName("孔雀翎");
    book.setAuthor("古龙");

    bookDao.save(book);
  }
  @Test
  void testupdate() {
    Book book = new Book();
    book.setName("笑傲江湖");
    book.setAuthor("金庸");
    book.setId(1);
    bookDao.saveAndFlush(book);
  }
  @Test
  void testdelete() {
    bookDao.deleteById(1);
  }

  @Test
  void testFind() {
    System.out.println(bookDao.findById(4).toString());
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧