美文网首页
Spring Boot 入门系列(七) 使用 JPA

Spring Boot 入门系列(七) 使用 JPA

作者: 回文体文回 | 来源:发表于2019-08-03 14:51 被阅读0次

文章使用版本为 Spring Boot 2.1.x

前言

JPA是Java Persistence API的简称,是一种标准,具体实现交由各个厂商实现。Spring Data JPA 对其提供支持,内部实现是Hibernate。

使用JPA开发代码非常方便,只要写一个接口继承 JpaRepository 就可以实现基本的增删改查的功能,比如下面这样

public interface UserRepository extends JpaRepository<User, String> {

}

在大部分情况下都是使用单表操作时,使用JPA也是一个不错的选择,下面我们就来一起学习下吧。

添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/spring_boot_learn?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true&useSSL=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    hikari:
      minimum-idle: 2
      maximum-pool-size: 5
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

datasource的部分就不多讲了,我们主要来看一下jpa的配置部分

  • jpa.show-sql:这个很明显是控制是否显示SQL语句的,开发时我们可以选择true
  • jpa.hibernate.ddl-auto:这个是用来控制数据库表的生成策略,有以下几种值
    • create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
    • create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
    • update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
    • validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

虽然可以让程序自动生成表结构,但是我还是建议手写建表语句。

CREATE SCHEMA IF NOT EXISTS `spring_boot_learn` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

CREATE TABLE IF NOT EXISTS `spring_boot_learn`.`user` (
  `id` VARCHAR(37) NOT NULL COMMENT 'UUID',
  `username` VARCHAR(128) NOT NULL COMMENT '用户名',
  `age` INT(10) unsigned NOT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)  COMMENT ''
  )
ENGINE = InnoDB
COMMENT = '用户表';

创建实体

package org.schhx.springbootlearn.entity;

import lombok.Data;
import lombok.experimental.Accessors;

import javax.persistence.Entity;
import javax.persistence.Id;

@Data
@Accessors(chain = true)
@Entity
public class User {
    @Id
    private String id;

    private String username;

    private Integer age;

}

@Entity 表明是一个实体类
@Id 用来指明主键,如果使用自增主键,可以在主键上加上@GeneratedValue

创建数据访问接口

package org.schhx.springbootlearn.dao;

import org.schhx.springbootlearn.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRepository extends JpaRepository<User, String> {

    List<User> findByUsername(String username);
}

通过查看 JpaRepository 的源码我们可以发现,通用的增删改查的方法都已经有了,当然你也可以自己写一些方法,比如 List<User> findByUsername(String username),JPA会自动根据方法名来创建实现。

测试

package org.schhx.springbootlearn.dao;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.schhx.springbootlearn.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

import static org.junit.Assert.*;

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

    @Autowired
    private UserRepository userRepository;

    @Test
    @Transactional
    public void create() throws Exception {
        String id = UUID.randomUUID().toString();
        User user = new User().setId(id).setUsername("张三").setAge(20);
        User result = userRepository.save(user);
        System.out.println(result);
        Assert.assertNotEquals(null, result);
    }

    @Test
    @Transactional
    public void findByUserName() throws Exception {
        String id = UUID.randomUUID().toString();
        User user = new User().setId(id).setUsername("张三").setAge(20);
        userRepository.save(user);
        List<User> result = userRepository.findByUsername("张三");
        System.out.println(result);
        Assert.assertNotEquals(null, result);
    }

    @Test
    @Transactional
    public void findByExample() throws Exception {
        String id = UUID.randomUUID().toString();
        User user = new User().setId(id).setUsername("张三").setAge(20);
        userRepository.save(user);
        List<User> result = userRepository.findAll(Example.of(new User().setUsername("张三")));
        System.out.println(result);
        Assert.assertNotEquals(null, result);
    }
}

完整示例

相关文章

网友评论

      本文标题:Spring Boot 入门系列(七) 使用 JPA

      本文链接:https://www.haomeiwen.com/subject/sxhmzxtx.html