Spring Boot integrating Spring Data JPA introduction 01

Spring Data JPA: Introduction:
Spring Data is the framework that spring provides operation database, and Spring Data JPA is just a module based on JPA standard operation database under Spring Data framework.
Spring Data JPA: operate on data based on JPA standard. Simplify the code of persistence layer, only need to write interface.
Spring boot integrates Spring Data JPA
1. Add dependency:


2. Add application.yml configuration information:

#mysql database driver URL username password
#Database connection pool
#Forward engineering
#Console output sql
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
      ddl-auto: update
    show-sql: true

New database

3. Add entity class

@Table(name = "t_users")
public class Users {

     * @Id:Indicates that id is the primary key
     * @GeneratedValue: Generation strategy
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "age")
    private Integer age;
    @Column(name = "address")
    private String address;

4. Add persistent layer interface

 * Parameter 1: entity class to be mapped currently
 * Parameter 2: id primary key type in the entity class to be mapped currently
public interface UsersRepository  extends JpaRepository<Users,Integer> {

5. Add the coordinates of the test startup class in the pom file


6. Create a new startup class

public class SpringBootDataJpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDataJpaApplication.class, args);

Write test code
Under the test package, create a new com.gblfy.repository package (consistent with the java package structure above):
The new test class UsersRepositoryTest inherits the test class generated by Springboot. The advantage of this is that it does not need to add test annotation to each test class, but only inherits the common test class (the same principle as the interface implementation class)

public class UsersRepositoryTest {

    private UsersRepository usersRepository;

    public void saveUser(){
        Users u = new Users();

10. Operation effect diagram:

View database:
1. Generate T ﹣ users table
2. Whether to insert the data into the database successfully

Tags: Spring Database MySQL Java

Posted on Fri, 08 Nov 2019 08:39:05 -0800 by theeper