Spring Boot JPA Tutorial

JPA is Spring Boot official recommended database access components, which fully embodies the object-oriented programming ideas, a bit like the EFCore asp.net. JPA also abstract many of ORM.

From the start of this series, we need to use mysql database and other reference databases. Please prepare the relevant links. This chapter requires the following environment support:

  • mysql 5.6+
  • jdk1.8 +
  • spring boot 2.1.6
  • idea 2018.1

The project source code download

1 Data Preparation

Database tutorial series are using the same data as in the tutorial Spring Boot JDBC as the use of

Field Types of Primary key Explanation
id int Yes auto numbering
user_name varchar(100) no username
password varchar(255) no password
last_login_time date no Recently logged time
sex tinyint no Sex 0 male and 1 female 2 Other

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `last_login_time` datetime DEFAULT NULL,
  `sex` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
BEGIN;
INSERT INTO `t_user` VALUES (1, 'json', '123', '2019-07-27 16:01:21', 1);
INSERT INTO `t_user` VALUES (2, 'jack jo', '123', '2019-07-24 16:01:37', 1);
INSERT INTO `t_user` VALUES (3, 'manistal', '123', '2019-07-24 16:01:37', 1);
INSERT INTO `t_user` VALUES (4, 'landengdeng', '123', '2019-07-24 16:01:37', 1);
INSERT INTO `t_user` VALUES (5, 'max', '123', '2019-07-24 16:01:37', 1);
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

2 New Spring Boot engineering items

  1. File> New> Project, select the figure below Spring Initializrand then click [Next] Next
  2. Fill GroupId(package name), Artifact(project name) can be. Click Next
    groupId = com.fishpro
    artifactId = JPA
  3. The choice depends Spring Web Starterin front of the tick, tick SQL options Spring Data JPA, MySQL
  4. Project name is set spring-boot-study-jpa.

3 configuration dependent incorporated Pom.xml

If you've checked checked SQL options Spring Data JPA, MySQL, so no need to manually increase dependency.

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

4 JPA project configuration application.yml

server:
  port: 8086
spring:
  #通用的数据源配置
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo_test?useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    #这个参数是在建表的时候,将默认的存储引擎切换为 InnoDB 用的
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    #配置在日志中打印出执行的 SQL 语句信息。
    show-sql: true
    hibernate:
      #配置指明在程序启动的时候要删除并且创建实体类对应的表
      ddl-auto: create
  • spring.jpa.database-platform set org.hibernate.dialect.MySQL5InnoDBDialectthis parameter in the construction of the table when the engine is switched to the default storage with InnoDB
  • spring.jpa.show-sql configuration print out is set to true SQL statement is executed in the log information.
  • spring.jpa.hibernate.ddl-auto settings specified to be deleted when the program starts and creates corresponding entity class to create configuration table

5 writing sample code

This exemplary code structure with Spring Boot Mybatis tutorial is the same.

The difference is that code is easy and convenient in the name, JPA Dao put into a Repository, inherited CrudRepository.

This example includes a new page

  1. src/main/java/com/fishpro/jpa/controller/UserController.java 控制层 rest api
  2. src / main / java / com / fishpro / jpa / domain / UserDO.java entity object
  3. src / main / java / com / fishpro / jpa / dao / UserRepository.java Repository database access layer
  4. src / test / java / fishpro / com / UserRepositoryTest.java test class

5.1 New Entity Object UserDao.java

Based on the establishment of an entity object POJO, JPA should be noted that there is a difference with Mybatis

  1. Entity class requires the use of annotations marked @Entity
  2. Properties required for tagging entity class, the primary key are denoted with the @Id
  3. Using the primary key are denoted @Column

/**
 * 用户实体类
 * */
@Entity
@Table(name="t_user")
public class UserDO {
    @Id
    private Integer id;
    @Column(name="user_name",length = 200)
    private String userName;
    @Column(name="password",length = 200)
    private String password;
    @Column(name="sex")
    private Integer sex;
    @Column(name="last_login_time")
    private Date lastLoginTime;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getLastLoginTime() {
        return lastLoginTime;
    }

    public void setLastLoginTime(Date lastLoginTime) {
        this.lastLoginTime = lastLoginTime;
    }
}

5.2 New warehouse interface class UserRepository

Warehouse interface class UserRepositoryis our common Dao interface to note that JPA storage interface requires

  1. Use @Repositoryannotations
  2. inherit JPARepository
  3. UserRepository Without writing any code, can be achieved CRUD
@Repository
public interface UserRepository extends JPARepository<UserDO,Integer> {

}

6 test of written UserRepository

About tests can be found using the Spring Boot RestApi test the tutorial Mock

In src/test/java/com/fishpro/jpa/the new case UserRepositoryTest.javause @RunWith(SpringRunner.class)and @SpringBootTestannotation label classes.

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

}

6.1 new user data

Initialize an object UserDO Insert test process

/**
     * 初始化一个对象 UserDO 测试Insert过程
     * */
    @Before
    public void before(){
        UserDO userDO=new UserDO();
        userDO.setId(1);
        userDO.setUserName("fishpro");
        userDO.setSex(1);
        userDO.setLastLoginTime(new Date());
        userDO.setPassword("passWord");
        userRepository.save(userDO);
    }

6.2 single data query

@Test
    public void testFind(){
        Optional<UserDO> optionalUserDO=userRepository.findById(1);
        if(optionalUserDO.isPresent()){
            UserDO userDO=optionalUserDO.get();
            System.out.println("testFind user"+userDO.getUserName());
        }

    }

6.3 query multiple data

@Test
    public void testFindAll(){
        List<UserDO> list=userRepository.findAll();
        for (UserDO user:list
             ) {
            System.out.println("user_name:"+user.getUserName());
        }
    }

6.4 update data

@Test
    public void testUpdate(){
        Optional<UserDO> optionalUserDO=userRepository.findById(1);
        if(optionalUserDO.isPresent()){
            UserDO userDO=optionalUserDO.get();
            userDO.setUserName("fishpro001");
            userRepository.save(userDO);
            System.out.println("testFind user"+userDO.getUserName());
        }

    }

6.5 to delete data

@After
    public void after(){
        userRepository.deleteById(1);
        userRepository.deleteById(2);
        userRepository.deleteById(3);
    }

Consideration about 7

7.1 the primary key is provided

Suppose we define user roles table includes the userId, roleId are two primary keys.

  1. Define a primary key class
public class UserRoleKey implements Serializable {
    private Integer userId;
    private Integer roleId;
}
  1. Class definition entities
    Note entity class is used @IdClassannotation to achieve a composite primary key definition
@Entity
@Table(name="t_user_role")
@IdClass(UserRoleKey.class) //注意这里是引入了 定义的符合主键类
public class UserRoleDO {
    @Id
    private Integer userId;
    @Id
    private Integer roleId;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }
}

7.2 Custom Query

Guess you like

Origin www.cnblogs.com/fishpro/p/spring-boot-study-jpa.html