Simple implementation of spring boot + MySQL + JPA

Keywords: Database Spring Hibernate MySQL

1 First we need to introduce the packages we need in pom.xml

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

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

I won't mention the pom above. I believe you can understand that one is mysql connection and the other is jpa reference.

Configuration in application.xml: database connection information (if embedded database is not needed), automatic creation of table structure settings, such as using mysql, as follows:

spring.datasource.url=jdbc:mysql://xxxxx:3306/test
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update

Above is your mysql database connection. spring.jpa.hibernate.ddl-auto is the configuration attribute of hibernate. Its main function is to automatically create, update and verify the database table structure. Several configurations of this parameter are as follows:

  • create: Every time hibernate is loaded, the generated tables are deleted, and then the new tables are regenerated according to your model class. Even if there are no changes twice, they should be executed in this way. This is an important reason for the loss of database table data.
  • create-drop: Each time hibernate is loaded, tables are generated according to the model class, but once session Factory is closed, tables are automatically deleted.
  • Update: the most commonly used attribute, the first time hibernate is loaded according to the model class will automatically establish the structure of the table (the premise is to establish a database first), and later when hibernate is loaded according to the model class automatically update the table structure, even if the table structure changes, but the table row still exists will not delete the previous row. It should be noted that when deployed to the server, the table structure will not be established immediately, but will not be established until the application runs for the first time.
  • validate: Every time hibernate is loaded, validation creates the database table structure, compares it with the tables in the database, does not create new tables, but inserts new values.

3 Creating Entities
Create a User entity, including id (primary key), name (name), age (age) attributes, which will be mapped to database tables through ORM framework. Because spring.jpa.hibernate.ddl-auto is configured, the framework will automatically create the corresponding tables in the database when the application starts.

package com.fy.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;

/**
 * @author : lqf
 * @description : Test entity
 * @date : Create in 15:26 2018/5/4
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class User implements Serializable {

    /**
     * Primary key id
     */
    @Id
    @GeneratedValue
    private Integer id;

    /**
     * Full name
     */
    @Column(name = "name", nullable = false)
    private String name;

    /**
     * Age
     */
    @Column(name = "age", nullable = false)
    private Integer age;
}

Instead of providing get, set, constructor, etc., the above entity class uses a lot of annotations, which are explained here (explicit automatic skipping)

  • @ Data: Automatically add @ToString, @EqualsAndHashCode, @Getter method for all fields, add @Setter for non-final fields, and @RequiredArgsConstructor
  • @ NoArgs Constructor: Automatic generation of parametric constructors
  • @ AllArgs Constructor: Automatic Generation of Full Parametric Constructors
  • @ Builder: Used in classes, constructors, methods, to provide you with complex builder APIs, so that you can call Person.builder().name("Adam Savage"). city("San Francisco"). job("Mythbusters"). job("Unchained Reaction"). build().
  • @ Entity: Comments on entities. Any Hibernate mapping object should have this annotation
  • @ Table: Declares that this object maps to the database's data tables by which the names of tables (talbe), catalogs, and schema s can be specified for entities. This annotation is not required, and if not, the system uses the default value (the short class name of the entity).

4 Create Data Access Interface
The following code is to create a corresponding Repository interface for the User entity to access the entity's data:

package com.fy.repository;

import com.fy.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

/**
* @author : lqf
* @description : Test User repository
* @date : Create in 15:35 2018/5/4
*/
public interface UserRepository extends JpaRepository<User,Long>{

    User findByName(String name);


    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);
}

In the example above, we can see the following two functions:

  • User findByName(String name)
  • User findByNameAndAge(String name, Integer age)

They implement querying User entity by name and User entity by name and age respectively. We can see that we have completed two conditional query methods without any kind of SQL statement. This is one of the major features of Spring-data-jpa: creating queries by parsing method names.

In addition to creating queries by parsing method names, it also provides the ability to create queries by using the @Query annotation. You only need to write JPQL statements and map parameters specified by @Param through similar ": name", just like the third findUser function in the example.

package com.fy;

import com.fy.domain.User;
import com.fy.repository.UserRepository;
import org.junit.Assert;
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;

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

   @Autowired
   private UserRepository userRepository;

   @Test
   public void contextLoads() {
      // Establish10Bar record
      userRepository.save(new User("AAA", 10));
      userRepository.save(new User("BBB", 20));
      userRepository.save(new User("CCC", 30));
      userRepository.save(new User("DDD", 40));
      userRepository.save(new User("EEE", 50));
      userRepository.save(new User("FFF", 60));
      userRepository.save(new User("GGG", 70));
      userRepository.save(new User("HHH", 80));
      userRepository.save(new User("III", 90));
      userRepository.save(new User("JJJ", 100));

      // Test findAll and query all records
      Assert.assertEquals(10, userRepository.findAll().size());

      // Test findByName and query User with the name FFF
      Assert.assertEquals(60, userRepository.findByName("FFF").getAge().longValue());

      // Test findUser and query User with the name FFF
      Assert.assertEquals(60, userRepository.findUser("FFF").getAge().longValue());

      // Test findByName AndAge, query the name FFF and age60Of User
      Assert.assertEquals("FFF", userRepository.findByNameAndAge("FFF", 60).getName());

      // Test to delete User with the name AAA
      userRepository.delete(userRepository.findByName("AAA"));

      // Test findAll, query all records, and verify that the deletion above is successful
      Assert.assertEquals(9, userRepository.findAll().size());

   }

}

At this point, a simple spring boot + MySQL + JPA is implemented.

Posted by dunnsearch on Sun, 19 May 2019 14:26:17 -0700