• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Spring boot 2. X basic tutorial: using spring data JPA to access MySQL

King Wang

1 月 3, 2022

The first article in the data access chapter 《Spring Use in JdbcTemplate Access database 》 in , We’ve shown you how to use Spring Boot The most basic jdbc Module to realize data read and write operation of relational database . So combine Web The content of the development chapter , We can use it JDBC Module and Web Function of the module , It is used to complete a back-end application suitable for many simple application scenarios .

However, when we have some development experience , It’s not hard to find out , In the actual development process , Most operations on the database can be summed up as :“ Additions and deletions ”. In terms of the most common single table operation , Except tables and fields are different , The sentences are almost the same , Developers need to write a lot of similar and boring statements to complete business logic .

In order to solve these boring data operation statements , There are so many excellent frameworks , such as :Hibernate. Through integration Hibernate, We can operate Java Entity to complete the operation of data , With the help of the framework , Yes Java Changes to entities will eventually be automatically mapped to database tables .

stay Hibernate With the help of the ,Java After the entity mapping to database table data is completed , And then we can further solve the problem of abstraction Java Physical basic “ Additions and deletions ” operation , We usually encapsulate a template in a generic way Dao To abstract and simplify , But it’s still not very convenient , We need to write an inherited generic template for each entity Dao The interface of , Then write the implementation of this interface . Although some basic data access can be well reused , But there’s a stack for each entity in the code structure Dao Interface and implementation of .

Due to template Dao The implementation of the , Make these specific entities Dao The layers have changed very much “ thin ”, There are some concrete entities Dao The implementation may be all about templates Dao A simple agent of , And often such implementation classes may appear on many entities .Spring Data JPA The emergence of the can make such a very “ thin ” The data access layer of is just a way to write interface . such as , 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 just need to write an inheritance from JpaRepository Data access can be done through the interface of , Here is a concrete example to experience Spring Data JPA The powerful function that brings to us .

Use steps

because Spring Data JPA Depend on Hibernate. If you are right about Hibernate Have a certain understanding , The following content can be easily understood and used . If you still Hibernate Novice , You can get started as follows , I suggest that you go back to study Hibernate To help the understanding and further use of this part .

Engineering configuration

stay pom.xml Add related dependencies , Add the following :

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

stay application.xml Middle configuration : Database connection information ( If you use an embedded database, you don’t need )、 Automatically create table structure settings , For example, using mysql The situation is as follows :

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

spring.jpa.properties.hibernate.hbm2ddl.auto yes hibernate Configuration properties of , Its main function is to : Automatically create 、 to update 、 Validate the database table structure . Several configurations of this parameter are as follows :

  • create: Each load hibernate The last generated table is deleted , Then follow your example model Class to generate a new table , Do this even if nothing changes twice , This is an important cause of database table data loss .
  • create-drop: Each load hibernate According to the model Class generation table , however sessionFactory A closed , The table is automatically deleted .
  • update: The most commonly used attribute , First load hibernate According to the model Class automatically sets up the structure of the table ( The premise is to establish a good database first ), After loading hibernate According to the model Class automatically updates the table structure , Rows in the table still exist even if the structure of the table has changed and previous rows are not deleted . Note that when deployed to the server , Table structures are not built immediately , It doesn’t do that until the application runs for the first time .
  • validate: Each load hibernate when , Verify that the database table structure is created , Only the tables in the database are compared , No new tables are created , But a new value is inserted .

So far, the basic configuration has been completed , If you are in Spring The next integration used it , Believe that you have felt Spring Boot The convenience of :JPA The traditional configuration of persistence.xml In file , But here we don’t need . Of course , It’s best to build the project as mentioned earlier Best practice engineering structure To organize , This ensures that all configurations can be scanned by the framework .

Create entities

Create a User Entity , contain id( Primary key )、name( full name )、age( Age ) attribute , adopt ORM Framework it will be mapped to database tables , Because of the configuration hibernate.hbm2ddl.auto, When the application starts, the framework will automatically create the corresponding table in the database .

@Entity
@Data
@NoArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}

  • @Entity The annotation marks User Class is a persistent entity
  • @Data and @NoArgsConstructor yes Lombok The annotations in . Used to generate parameters automatically Set、Get Functions and parameterless constructors . If you are right about Lombok I don’t know yet , Take a look at this article :Java Develop artifact Lombok The use and principle of
  • @Id and @GeneratedValue Used to identify User Corresponding to the primary key in the database table

Be careful : In addition to these notes , There are also a lot of annotations to refine the configuration mapping relationship , No specific introduction here . There will be a special article to introduce the common notes . Readers can also read by themselves Hibernate To learn how to use these annotations in detail .

Create a data provider

The following for User Entity creation corresponding Repository The interface implements data access to the entity , The following code :

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);
}

stay Spring Data JPA in , You only need to write an interface like the one above to realize data access . No longer like we used to write interfaces, we need to write interface implementation classes ourselves , Directly reduced our list of documents .

Next to the top UserRepository Make some explanations , The interface is inherited from JpaRepository, By looking at JpaRepository Interface API file , You can see that the interface itself has been created (save)、 to update (save)、 Delete (delete)、 Inquire about (findAll、findOne) And so on , Therefore, data access for these basic operations does not need to be defined by the developers themselves .

In our actual development ,JpaRepository The interface defined by the interface is often not enough or the performance is not optimized enough , We need to further implement more complex queries or operations . Because this article focuses on Spring Boot The integration of spring-data-jpa, Here is a brief introduction spring-data-jpa What makes us excited , Let’s talk about it separately later spring-data-jpa Common use in .

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

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

They respectively achieve the press name Inquire about User Entity and press name and age Inquire about User Entity , You can see that we don’t have any classes here SQL Statement completes two conditional query methods . This is it. Spring-data-jpa One of the characteristics of : Create a query by parsing the method name .

In addition to creating queries by parsing method names , It is also available through the use of @Query Annotations to create queries , You just need to write JPQL sentence , And through something like “:name” To map @Param Specified parameters , Like the third in the example findUser The function is the same .

Spring Data JPA The ability to do more than that mentioned in this article , Because this article mainly introduces the integration , about Spring Data JPA The common usage of . Such as @Modifying operation 、 Sort by page 、 Native SQL Support and with Spring MVC The combination of the use of and so on will not be detailed in this article , Dig a hole here first , Fill in the hole later , If you are interested in these, you can pay attention to my blog or short book , You are also welcome to leave a message and exchange ideas .

unit testing

After completing the data access interface above , The Convention is to write the corresponding unit test to verify whether the content is correct . There is no more introduction here , Mainly through data operation and query to repeatedly verify the correctness of the operation .

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
// establish 10 Bar 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, Check all records
Assert.assertEquals(10, userRepository.findAll().size());
// test findByName, Query name is FFF Of User
Assert.assertEquals(60, userRepository.findByName("FFF").getAge().longValue());
// test findUser, Query name is FFF Of User
Assert.assertEquals(60, userRepository.findUser("FFF").getAge().longValue());
// test findByNameAndAge, Query name is FFF And the age is 60 Of User
Assert.assertEquals("FFF", userRepository.findByNameAndAge("FFF", 60).getName());
// Test delete name as AAA Of User
userRepository.delete(userRepository.findByName("AAA"));
// test findAll, Check all records , Verify that the deletion above was successful
Assert.assertEquals(9, userRepository.findAll().size());
}
}

Expanding reading : About Spring Data

Spring Data JPA stay Spring It’s actually a secondary project in the family , It belongs to Spring Data This top project . Readers can take a look at the introduction of this project , In addition to covering the abstraction of relational databases , In fact, there are many other data storage middleware implementations , For example, we often use Redis、MongoDB、Elasticsearch etc. .

If you look for a few more projects to see a simple example of them , You’ll find that : No matter what data storage products you want to access , They are almost all encoded in the same way ! This is it. Spring Data The charm of this project ! By abstracting data access operations to mask details , Implement details in different sub projects . Let developers just learn to use Spring Data, Can learn the operation of various data storage conveniently and quickly . therefore , about Spring Data, I highly recommend Java Developers can learn 、 Even read the important framework of the source code . although , At present, many large Internet companies will not choose it ( Most performance considerations , There are not many people who can really use it well ) As the main development framework , But the abstract idea behind it is worth learning . also , When doing some non high concurrency projects , This is just a quick development artifact , It can help us write a lot less code !

More free tutorials in this series 「 Click to enter the summary Directory 」

Code example

For an example of this article, see the following in the warehouse chapter3-4 Catalog :

  • Github:https://github.com/dyc87112/SpringBoot-Learning/
  • Gitee:https://gitee.com/didispace/SpringBoot-Learning/

If you think this article is good , welcome Star Support , Your concern is the driving force of my persistence !

Welcome to my official account. : Program the ape DD, Get exclusive learning resources and daily dry goods push .

If you are interested in my topic content , You can also follow my blog :didispace.com

发表回复