Using JPA in Spring Boot projects

1. Integrate Spring Data JPA

Spring Boot provides the starter spring-boot-starter-data-jpa. You only need to add starters to use JPA in the project. The following step by step demonstrates the configuration required to integrate Spring Data JPA.

Step 01 Add JPA dependency.

First create a new Spring Boot project and add JPA-related dependencies to the project's pom.xml. The specific code is as follows:

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

In the above example, in addition to referencing spring-boot-starter-data-jpa, you also need to rely on the MySQL driver mysql-connector-java.

Step 02 Add configuration file.

Configure the basic related properties of the data source and JPA in application.properties. The specific code is as follows:

spring.datasource.url=jdbc:mysql://Localhost:3306/ceshi?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#JPA配置
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#SQL输出
spring.jpa.show-sql=true
#format 下SQL输出
spring.jpa.properties.hibernate.format_sql=true

Among the above parameters, it is mainly to configure the database connection and JPA properties. The following focuses on analyzing the four configurations in JPA.

1) spring.jpa.properties.hibernate.hbm2ddl.auto: This configuration is more commonly used to configure the specific behavior of entity classes to maintain the database table structure. When the service is started for the first time, the corresponding table will be generated in the database. When the service is started subsequently, if the entity class has added attributes, the corresponding fields will be added to the data, and the original data will still exist.

  • update: A commonly used attribute that indicates that when the attributes of the entity class change, the table structure will be updated accordingly.
  • create: means to delete the last generated table at startup and regenerate the table based on the entity class. The data in the previous table will be cleared.
  • create-drop: Indicates that the table is generated based on the entity class at startup, but the table will be deleted when the sessionFactory is closed.
  • validate: Indicates verifying whether the entity class and data table are consistent at startup.
  • none: Do nothing.

2) spring.jpa.show-sql: Indicates that hibernate prints the real SQL statement on the console during operation to facilitate debugging.

3) spring.jpa.properties.hibernate.format_sql: Represents the formatted output JSON string for easy viewing.

4) spring.jpa.properties.hibernate.dialect: Specify the storage engine that generates table names as InnoDB.

Step 03 Add entity class.

First, create the User entity class, which is an entity class and also a class that defines the table structure in the database. The sample code is as follows:

@Entity
@Table(name= "Users")
public class User {
    
    
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Long id;
    @Column(length = 64)
    private String name;
    @Column(length = 64)
    private String password;
    private int age;

    public User() {
    
    

    }
    public User(String name,String password, int age) {
    
    
        this.name=name;
        this.password=password;
        this.age=age;
    }

    public Long getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getPassword() {
    
    
        return password;
    }

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

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

In the above example, the @Table annotation is used to map the table in the database, and the @Column annotation is used to map the fields in the database. The specific instructions are as follows:

1) @Entity: A required annotation, stating that this class corresponds to a database table.

2) @Table: Optional annotation, which declares the table information corresponding to the database entity, including table name, index information, etc. It is declared here that the table name corresponding to this entity class is Users. If not specified, the table name and entity name remain consistent and are used in conjunction with the @Entity annotation.

3) @Id annotation: declares the attribute corresponding to the entity's unique identifier.

4) @Column annotation: The definition of table fields used to declare entity attributes. Each attribute of the default entity corresponds to a field in the table, and the field name is consistent with the attribute name by default. The type of the field automatically corresponds to the entity attribute type. The length of the character field is mainly declared here. If not declared in this way, the system will use 255 as the length of the field.

5) @GeneratedValue annotation: Set the automatic generation rules for database primary keys. The strategy attribute provides 4 values:

  • AUTO: The primary key is controlled by the program and is the default option.
  • IDENTITY: The primary key is automatically generated by the database, that is, the database ID is automatically incremented. Oracle does not support this method.
  • SEQUENCE: Generate the primary key through the sequence of the database, and specify the sequence name through the @SequenceGenerator annotation. MySQL does not support this method.
  • TABLE: Generate primary keys through a specific database table. Using this strategy can make the application easier to migrate to the database.

In addition to the @Entity annotation, @Table annotation, etc. used above, there are also some commonly used entity annotations. The specific description is shown in Table 9-1. These annotations are used to describe the correspondence between entity objects and database fields. It should be noted that there are differences between JPA and MyBatis, so do not confuse them.

Insert image description here
Step 04 Test verification.

The above steps are all the configurations for integrating JPA. After the configuration is completed, start the project and you will see the content shown in the log as shown in the figure.

Insert image description here
As can be seen from the figure, the system automatically connects to the database after startup, creates a data table structure, and prints out the executed SQL statements. If you check the database, you can see that the corresponding Users table in the database has also been created successfully, indicating that the project has successfully integrated JPA and created the entity table.

2. Introduction to JpaRepository

JpaRepository is a very important class in Spring Data JPA. It inherits from Spring Data's unified data access interface - Repository , and implements complete data operation methods such as adding, deleting, modifying, and querying. JpaRepository provides more than 30 default methods, which can basically meet the database operation functions in the project.

JpaRepository is the key interface to implement Spring Data JPA technology to access the database. JpaRepository inherits from the PagingAndSortingRepository interface, and the PagingAndSortingRepository interface inherits from the CrudRepository interface. CrudRepository and Repository interfaces are common interfaces at the bottom of Spring Data, defining almost all database interface methods and unifying data access operations.

In addition, JPA provides very complete data query functions, including custom queries, custom SQL, named queries and other data query methods.

3. Practical combat: Implementing personnel information management module

JpaRespository implements complete data operations such as adding, deleting, modifying, and checking by default. Just define a Repository data access interface and inherit the JpaRepository class. The following demonstrates the implementation of the user management module by using the previously created User class and table to implement the functions of adding, deleting, modifying, and checking users.

1. Define Repository

First create the UserRepository interface and add the @Repository annotation, and then inherit the JpaRepository class. You can realize all the functions of the personnel information management module without writing any code. The specific sample code is as follows:

@Repository
public interface UserRepository extends JpaRepository<Users, Long> {
    
    

}

We see that although UserRepository has no methods defined, after inheriting JpaRepository, it naturally has all the methods in JpaRepository.

2. Implement new addition, modification, deletion and query

(1) New

Next, create the UserRepositoryTests unit test class and implement the user's new test method. The sample code is as follows:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTest {
    
    
    @Resource
    private UserRepository userRepository;

    @Test
    public void testSave() {
    
    
        User user = new User("ysxq","123456",40);
        userRepository.save(user);
    }
}

In the above example, the UserRepository object is injected into the UserRepositoryTests unit test class, and then the JpaRespository pre-generated save() method is used to implement the function of saving personnel data. As shown below:

Insert image description here

Insert image description here

(2) Modification

Use the save() method for both modification and addition, and just pass in the data entity. JPA automatically modifies user data based on the primary key id. The sample code is as follows:

    @Test
    public void testUpdate() {
    
    
        User user = userRepository.findById(1L).get();
        user.setPassword("z123456");
        userRepository.save(user);
    }

(3) Delete

Deletion is also very simple. The delete() method pre-generated by JpaRespository is used. The object can be deleted directly, and the deleteByXXX method can also be used. The sample code is as follows:

    @Test
    public void testDetle() {
    
    
        User user = new User("ysxq","123456",40);
        userRepository.delete(user); 
    }

Insert image description here

(4) Inquiry

JPA has very complete support for data query. There are pre-generated findById(), findAll(), findOne() and other methods. You can also use customized simple queries and customize SQL queries. The sample code is as follows:

    @Test
    public void testSelect() {
    
    
        userRepository.findById(1L);
    }

3. Verification testing

Click Run Test or right-click on the method and select the Run 'UserRepositoryTest' command to run all test methods. The results are as shown in the figure.

Insert image description here
The results show that the unit tests for adding, deleting, modifying, and querying personnel information all run successfully, and the corresponding query results are output, indicating that the personnel information management function is implemented using JPA.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132753289