My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

spring boot jpa data access

jonelere's photo
jonelere
·Jul 3, 2018

In the actual development process, the operation of the database is nothing more than "additions, deletions and changes". In terms of the most common single-table operations, the statements are similar except that the tables and fields are different. Developers need to write a lot of similar and boring statements to complete the business logic.

In order to solve these large and boring data manipulation statements, our first thought is to use the ORM framework, such as: Hibernate. After integrating Hibernate, we finally map the data changes to the database tables by manipulating the Java entities.

In order to solve the basic "addition, deletion, and change" operations of abstract Java entities, we usually encapsulate a template Dao in a generic way for abstraction, but this is still not very convenient. We need to write an inheritance for each entity. The interface of the type template Dao, and then write the implementation of the interface. Although some basic data access can be well reused, there will be a bunch of Dao interfaces and implementations for each entity in the code structure.

Due to the implementation of the template Dao, the Dao layer of these concrete entities has become very "thin". Some Dao implementations of specific entities may be completely simple agents for the template Dao, and often such implementation classes may appear in many entities. on. The emergence of Spring-data-jpa is enabling such a "thin" data access layer to be written as a layer of interface. For example, the following example:

Public  interface  UserRepository  extends  JpaRepository < User , Long > {

    User findByName (String name) ;

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

}

We only need to write an inherited JpaRepositoryinterface to complete the data access. Let's take a concrete example to experience the powerful features that Spring-data-jpa brings to us.

Use example Because Spring-data-jpa depends on Hibernate. If you have some understanding of Hibernate, the following content can be easily understood and used to use Spring-data-jpa. If you are new to Hibernate, you can start by following the steps below, and then suggest to go back and learn Hibernate to help understand and further use this part.

Engineering configuration In pom.xmladd related dependencies, add the following:

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

In application.xmlthe configuration: database connection information (such as the use of embedded database is not required), automatic creation of the table structure settings, such as the use of mysql as follows:

Spring.datasource.url=jdbc:mysql://localhost:3306/ test
 spring.datasource.username=root 
spring.datasource.password=root 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

spring.jpa.properties.hibernate.hbm2ddl.aut.. the hibernate configuration properties, its main role is: automatically create, update, verify the database table structure. Several configurations of this parameter are as follows:

createEvery time hibernate is loaded, the last generated table will be deleted, and then the new table will be regenerated according to your model class, even if there are no changes twice, this is an important reason for the loss of database table data.

create-drop: Each time hibernate is loaded, the table is generated according to the model class, but once the sessionFactory is closed, the table is automatically deleted.

update: The most commonly used property, the first time you load hibernate, according to the model class will automatically establish the structure of the table (provided that the database is built first), after loading hibernate, the table structure is automatically updated according to the model class, even if the table structure changes, but the table The line still exists and will not delete the previous line. It should be noted that when deployed to the server, the table structure will not be established immediately, it will wait until the application is run for the first time.

validate: Every time you load hibernate, verify that the database table structure is created, only compare with the tables in the database, will not create a new table, but will insert new values.

Now that you have completed the basic configuration, if you have integrated it in Spring, I believe you have already felt the convenience of Spring Boot: JPA's traditional configuration is in the persistence.xmlfile, but we don't need it here. Of course, it's best to organize the project in accordance with the best-practice engineering structure mentioned earlier to ensure that the various configurations are scanned by the framework.

Create entity Create a User entity containing id (primary key), name (name), age (age) attributes, which will be mapped to the database table through the ORM framework. Due to the configuration hibernate.hbm2ddl.auto, the framework will automatically create the database when the application is launched. Corresponding table.

@Entity 
public  class  User  {

    @Id @GeneratedValue private Long id;



    @Column (nullable = false ) private String name;


    @Column (nullable = false ) private Integer age;


    // omit the constructor

    // omit getter and setter

}

Create a data access interface The following creates a corresponding Repositoryinterface for the User entity to implement data access to the entity, as follows:

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 Spring-data-jpa, you only need to write an interface like the above to achieve data access. No longer need to write the interface implementation class ourselves when we have written the interface, which directly reduces our file list.

Let's UserRepositoryexplain the above . The interface inherits JpaRepository. By looking JpaRepositoryat the API documentation of the interface, you can see that the interface itself has been created, saved, deleted, and queried (findAll, findOne). ) Basic functions such as operations, so data access to these basic operations does not require developers to define them themselves.

In our actual development, the JpaRepositoryinterface defined by the interface is often not enough or the performance is not optimized enough. We need to further implement more complicated queries or operations. Since this article focuses on integrating spring-data-jpa in the spring boot, here is a brief introduction to the features that make us excited in spring-data-jpa, and then we will start with a discussion about the common use of spring-data-jpa.

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

User findByName(String name) User findByNameAndAge(String name, Integer age) They respectively implement the query of the User entity by name and the User entity by name and age. We can see that we have completed two conditional query methods without any SQL statements. This is one of the great 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 @Query annotations. You only need to write JPQL statements and map the parameters specified by @Param by something like ":name", like the example The same is true for the three findUser functions.

The ability of Spring-data-jpa is far more than the one mentioned in this article. Because this article is mainly based on integration, the use of Spring-data-jpa only introduces the common usage. Such things as @Modifying operation, page sorting, native SQL support, and use with Spring MVC are not detailed in this article. Here we will dig a pit and fill in the pits later. If you are interested in these, you can follow me. Blogs or short books, also welcome everyone to exchange ideas.

unit test After completing the above data access interface, it is customary to write the corresponding unit test to verify that the content written is correct. There is not much to introduce here, and the correctness of the operation is repeatedly verified through data manipulation and query.

@RunWith (SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration (Application.class) 
public  class  ApplicationTests  {

    @Autowired private UserRepository userRepository;


    @Test public void test () throws Exception {


        // Create 10 records
         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, query all records
         Assert.assertEquals( 10 , userRepository.findAll().size());

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

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

        // Test findByNameAndAge, query User         Assert.assertEquals with name FFF and age 60
 ( "FFF" , userRepository.findByNameAndAge( "FFF" , 60 ).getName());

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


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

    }


}

source links:

spring boot jpa example

[ spring boot] (en.wikibooks.org/wiki/Java_Programming/Spri..)