cool hit counter SpringBoot and Kotlin simplify the data access layer using Spring-data-jpa_Intefrankly

SpringBoot and Kotlin simplify the data access layer using Spring-data-jpa

Spring Boot and Kotlin Using JdbcTemplate to connect to MySQL" describes a basic approach to data access, combined with building a RESTful API and using the Thymeleaf template engine to render the contents of the Web view can already complete the task of App server and Web site development.

However, in the actual development process, the operation of the database is nothing more than "add, delete, change and check". In the case of the most common single-table operations, the statements are similar except that the tables and fields are different, and developers need to write a lot of similar and boring statements to complete the business logic.

To solve these large number of boring data manipulation statements, the first thing that comes to our mind is to use an ORM framework such as : Hibernate. After integrating Hibernate, we end up mapping data changes to database tables in the same way we manipulate Java entities.

In order to solve the abstraction of the basic "add, delete, change" operations of each Java entity, we usually encapsulate a template Dao in a generic way to simplify the abstraction, but this is still not very convenient, we need to write an interface for each entity inherited from the generic template Dao, and then write the implementation of the interface. While some basic data access can already be well reused, there are a bunch of Dao interfaces and implementations in the code structure for each entity.

Due to the implementation of the template Dao, the dao layer of these concrete entities has become very "thin", and some concrete entities' Dao implementations may be simple proxies for the template Dao, and often such implementation classes may appear on many entities. Spring-data-jpa is a way to turn an already "thin" data access layer into just a layer of interface writing. For example, the following example.

Data access can be done simply by writing an interface that inherits from JpaRepository. Here is a concrete example to experience the power that Spring-data-jpa brings to us.

Since Spring-data-jpa depends on Hibernate. If you have some knowledge of Hibernate, the following will make it effortless to read and get started with Spring-data-jpa. If you are still new to Hibernate, you can get started as follows, and then it is recommended to go back and learn Hibernate to help with this part of understanding and further use.

Engineering Configuration

Add the relevant dependencies in Add the following.

If you use jpa you must add the plugin

Like the kotlin-spring plugin, kotlin-jpa is a plugin that is included on top of no-arg. The plugin automatically specifies @Entity, @Embeddable and @MappedSuperclass no-arg annotations.

If the Gradle plugins DSL used


Configure in: database connection information (not required if using an embedded database), settings for automatic creation of table structures, e.g. for the use of mysql as follows.

is a configuration property of hibernate, whose main purpose is: to automatically create, update, and validate database table structures. Several configurations of this parameter are as follows.

create: each time you load hibernate will delete the last generated table, and then according to your model class to re-generate a new table, even if nothing has changed twice to perform so, which is a major cause of database table data loss.

create-drop: Generate a table based on the model class each time hibernate is loaded, 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 build up the structure of the table (provided that the database is first set up), later when you load hibernate according to the model class automatically update the table structure, even if the table structure has changed but the rows in the table still exist will not delete the previous rows. It is important to note that when deployed to the server, the table structure is not built up right away, it is waiting until the application is up and running for the first time.

validate: each time hibernate is loaded, validate creates the database table structure and will only compare it with the tables in the database, no new tables will be created, but new values will be inserted. This completes the base configuration, and if you have used it with Spring integration, I'm sure you've already felt the convenience of Spring Boot: the traditional configuration of JPA is in the persistence.xml file, but we don't need it here. Of course, it's best to build the project in a way that is organized according to the engineering structure of the best practices previously mentioned, so as to ensure that the various configurations are scanned by the framework.

Create entity

Creating a Data Access Interface

The following code creates the corresponding Repository interface for the User entity to implement data access to that entity.

In Spring-data-jpa, data access can be achieved by simply writing an interface like the above. We no longer need to write our own interface implementation classes, as we used to do when we wrote interfaces, directly reducing our list of files.

The following is some explanation of the above UserRepository, the interface inherits from JpaRepository, by looking at the JpaRepository interface API documentation, you can see that the interface itself has been implemented to create (save), update (save), delete (delete), query (findAll, findOne) and other basic operations of the function, so for these basic operations of data access will not need to be defined by the developer.

In our practical development, the interface defined by the JpaRepository interface is often not enough or not optimized for performance, and we need to further implement some more complex queries or operations. As this article focuses on integrating spring-data-jpa in spring boot, here is a brief introduction to the features that make us excited about spring-data-jpa, followed by a separate article on the common uses of spring-data-jpa.

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

fun findByName(name:String ):User

fun findByNameAndAge(name:String , age:Int ):User

They implement querying User entities by name and querying User entities by name and age, respectively, and you can see that we've done both conditional query methods here without any class SQL statements. This is one of the great features of Spring-data-jpa: creating queries by resolving method names.

In addition to creating queries by resolving method names, it also offers to create queries by using the @Query annotation, where you simply write JPQL statements and map the parameters specified by @Param with something like ":name", as in the third findUser function in the example.

unit test

After completing the data access interface above, The convention is to write the corresponding unit test to verify that what is written is correct。 I won't go into much detail here, Iteratively verify the correctness of operations mainly through data manipulation and queries。

For more Spring Boot and kotlin related content, please follow Spring Boot and kotlin in Action


Promotion and salary increase for Alltech Longtin

1、When will the cryptocurrency circle injustice cut Is there an end to the long bear market
2、Asia Pacific will account for over 60 of global robotics spending by 2021
3、New Tech News How are the 5 levels of processing power for selfdriving cars classified
4、Hacker I hacked into your computer and filmed you looking at adult websites now you want money or your face
5、How do you rate the lyrics of singer breakout Lee Quan sunnytwo

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送