SPRINGDATAJPA is a subproject of Spring Data that greatly reduces the JPA by providing JPA -based Repository As the amount of code for the data access scenario, you just need to write an interface that integrates the SPRINGDATAJPA internal definition to complete a simple CRUD operation, and the theory does not do much explaining, so let's start by explaining Springboot
Building projects
We use the IntelliJ idea tool to build a Springboot project, pre-import web, MySQL, JPA dependencies, we simply use a restcontroller to implement the JPA configuration, before also explained the simple use of JPA, Today detailed details of the specific content, the project structure as shown in 1:
Figure 1 Using the Druid data source
We use the configuration of the previous section to add the Druid data source configuration to our project, Copy the fourth chapter: Use Druid as the APPLICATION.YML configuration file in the Springboot project data source (add monitoring) project to our project resources, and modify the Pom.xml add Druid Data source dependency, as shown in 2:
Figure 2
APPLICATION.YML configuration file content as shown in 3 (specific code to the Code cloud: git.oschina.net/jnyqy/lessons):
Figure 3 Using Jparepository
We need to add an entity mapping to our test table before we configure the use of jparepository, for the convenience of this chapter we use the fourth chapter directly: Using Druid as the table structure and entities within the Springboot project data source (add monitoring), SQL file in the fourth chapter of the project source code resource directory, you can download the self-loading into the local database, the table structure as shown in 4:
Figure 4
Create the corresponding entity mappings according to the table structure, simple point, we use the single table operation,SPRINGDATAJPA and Hibernate syntax consistent inside are using JPA implementation. The mapping entity code is shown in 5:
Figure 5
The getter/setter method of Figure 5 above I did not post, self-tools to build on it. We are ready to do, below we create USERJPA interface, 5 I have created into the JPA directory, after creation is completed, add inherits from Jparepository,jparepository A generic interface parameter is required, the first parameter is an entity, the second is the type of the primary key, and theUSERJPA code is shown in 6:
Figure 6
Even if the interface of data access is implemented, we inherit the Jparepository interface and inherit the Pagingandsortingrepository interface and the Querybyexampleexecutor interface, what are the two interfaces for? The Pagingandsortingrepository interface also has an inherited from the Crudrepository interface. If you have a little knowledge of the architecture of friends should know, this design benefits.
Crudrepository
The interface contains the simplest crud, the Create, Read, Update, delete methods, and, of course, the count, exists method, as shown in 7:
Figure 7
If a self-defined JPA inherits the interface, it will have all the method implementations within the Crudrepository interface.
Pagingandsortingrepository
The interface inherits from the Crudrepository interface, which contains the implementation of the most basic crud method, with two methods added inside the interface, as shown in 8:
Figure 8
As the name implies, see interface names can be Lenovo, this method is designed for paging, of course, not just pagination and sorting methods.
Querybyexampleexecutor
Our jparepository interface inherits the interface, this interface provides conditional query, complex query method, can be queried by example way data, the source code as shown in 9:
Figure 9
We'll talk about QUERYDSL later, and then you'll know that the complex condition query provided by SPRINGDATAJPA is not the best choice.
Jparepository
Our custom interface inherits it, which means that our USERJPA has all the method implementations of the Jparepository interface and the parent interface, so we do not need to add any data manipulation code to complete the data operation. The Jparepository interface adds a corresponding method to the conditional query and save collection data, as shown in code 10:
Figure 10
Specific each method is used to do what, according to the name can be seen, here do not do one by one of the explanation. Below we need to test whether the USERJPA we have created can complete the data operation we said above.
Creating a test controller
We create a Usercontroller controller directly under the controller package, add the @restcontroller annotation support, we do not write the service layer code for convenience here, Inject USERJPA directly within the controller, as shown in code 11:
Figure 11
We have added the FindAll method of jparepository internal implementation within Usercontroller to query all user data, and we start the project test below.
Try running the test at first
When you run the project using the Springbootapplication mode, the console outputs the log prompt that the project failed to run, and here we need to comment out the scope property of the Spring-boot-starter-tomcat dependency.
Querying data
Try to access the user list address: 127.0.0.1:8080/list, you can see the page output a piece of data, which I manually added in the database, as shown in 12:
Figure 12 Adding data
We write a simple Add data method within Usercontroller, as shown in code 13:
Figure 13
We create a Userentity object within the Add method and assign values to all fields.
Note: There is a Save method in Springdatajpa, which is not just used to add data, but when we pass in the value of the primary key, the update data operation is done based on the value of the primary key.
We restart the project, try to access the 127.0.0.1:8080/add address, the interface output as shown in 14:
Figure 14
The interface gives us a hint that the data was added successfully, and we visited the list address to verify that it was added successfully, as shown in 15:
Figure 15
As you can see, the data has been added to the database through the Add method. because the updated operation and the addition of the same here does not explain, you just need to pass in the value of the primary key.
Delete data
We simply implement deleting a piece of data, adding a Delete method within Usercontroller, and accepting a primary key parameter, as shown in 16:
Figure 16
When we visit/delete, we can delete the corresponding data by passing in the UserId parameter, we will restart the project, access the 127.0.0.1:8080/delete?userid=5, and the interface input as shown in 17:
Figure 17
The data has successfully completed the delete operation.
The above operation is SPRINGDATAJPA for us, so far we have not written a SQL, so does SPRINGDATAJPA support custom SQL statements? The answer must be YES! Because it is powerful in this!
@Query Annotations for custom SQL
SPRINGDATAJPA internal there are two ways to implement the custom SQL function, we first to explain the use of annotations, later in the SPRINGDATAJPA core technology topic in more detail on the use of Entitymanager is how to complete the custom SQL, call stored procedures, View, and so on. Below we open the USERJPA interface and add custom queries older than 20 data, as shown in 18:
Figure 18
The @Query is the annotation used to configure the custom SQL, the following parameter Nativequery = True indicates the use of native SQL, if not configured, the default is False, then the HQL query method is used. We add method/age inside Usercontroller to test whether our custom SQL is valid, as shown in code 19:
Figure 19
Restart the project to access the 127.0.0.1:8080/age, as shown in the effect 20:
Figure 20@query with @modifying
From the name we can see that our @query annotations seem to be used only for querying, but if combined with @modifying annotations, you can complete the deletion, addition, and update operation of the data. Here we test the custom SQL to complete the operation of deleting data, I delete a data according to the name, password field, the interface code as shown in 21:
Figure 21
Let's write Usercontroller add the corresponding method to call the DeleteQuery interface method, as shown in 22:
Figure 22
Reboot under Project, Access address: 127.0.0.1:8080/deletewhere, interface output as shown in 23:
Figure 23
The interface unexpectedly has an exception, this is what is going on? You can see the thrown exception transcationrequiredexception, meaning that your current operation throws you a transaction exception that needs to be SPRINGDATAJPA custom SQL requires that transaction annotations @Transactionalbe added to the corresponding interface or the calling interface to enable transaction Automation management. Below we add @Transactional annotations within the USERJPA, restart the project to access the address just now, as shown in 24:
Figure 24
The interface has prompted me to delete the success, we look at the next console to see if the printed SQL is our custom, as shown in 25:
Figure 25
Our custom SQL has been successfully printed, the custom SQL has been added, the update operation is consistent with the deletion, all need to add @Query and @Modifying annotations in conjunction with.
Custom Baserepository
Project under normal circumstances not only inherit a jparepository interface, the next chapter we integrate SPRINGDATAJPA and QUERYDSL need to add multiple interface inheritance, then each of our business data interface to inherit a few of the same interface? The answer must be NO, of course, multiple inheritance is also possible, but for system design and code reusability is not the best choice!
We create a package name called base, add a Baserepository interface inside the package, and the interface inherits our Jparepository, as shown in code 26:
Figure 26
There's a new note,@NoRepositoryBean, what's this note for?
Spring Open source program apes should be more rigorous in naming rules, and we can almost judge the use of names from the name, if configured to inherit the Jparepository interface and other interfaces within the SPRINGDATAJPA interface, Sub-interfaces are not created as a repository proxy implementation class.
The business data interface that we create directly inherits Baserepository, and the inherited Subinterface has all of the jparepository methods implemented.
Paging Query
Paging is certainly essential for large systems, so how do we use paging to complete queries within SPRINGDATAJPA?
In general, we will create a baseentity, add several fields within the baseentity: sort by, order, current page, number of bars per page, and so on, let's create a parent class, as shown in code 27:
Figure 27
We modify userentity inheritance baseentity, and then add a few test data in the database, we do not have 20 pages per page, we create the query conditions to change to 2.
We open the Usercontroller add cutpage method, which is used as a paging query entry, ( Note: No service layer is added to the explanation of the article so all business logic is handled within the controller, Please do not write this in the official project. we add the corresponding paging logic within the cutpage method, as shown in 28:
Figure 28
Next we restart the project, Access address: 127.0.0.1:8080/cutpage?page=1, view the interface output effect as shown in 29:
Figure 29
Let's look at the output of the console, as shown in 30:
Figure 30
You can see that the console has printed two SQL for us, the first one is the SQL for paged query, and the second is the total number of SQL in the query table. The SPRINGDATAJPA internally encapsulates the quantity, which you can pass through the Page object, which is the findAll within the pagingandsortingrepository interface (pagerequest Request) method Gets the total number of bars, total pages, in the return value type of the
Sorting Data
We have added sorted fields and sorting methods above in baseentity, we can implement sort data by re-editing the Cutpage method, modifying Pagerequest creation method, adding Sort object to Pagerequest object. As shown in 31:
Figure 31
31 we can see that we have modified the sort field we used the default ID, (Note: the sort field here is not the name of the field in the database, but the attribute name within the entity) , and the sorting method is changed to reverse,SPRINGDATAJPA An enumeration type is added to the sort order, and the object is also enumerated when the sort object is created, because we baseentity Configure the string so that the enumeration object is returned with a step above the order.
Restart the project, and then access the paging path, the interface output effect as shown in 32:
Figure 32
You can see that the data has been shown in reverse order, and the log output of the console has also been added to the command by statement, as shown in 33:
Figure 33 Summary
In summary of the contents of this chapter has been explained, the content of this chapter is more than finished yesterday, please forgive me. This chapter mainly explains the basic operations of using SPRINGDATAJPA in the Springboot project, including: curd, paging, sorting, customizing SQL, defining Baserepository, transaction processing, and so on. The content of this chapter is not SPRINGDATAJPA comprehensive content, follow-up I will in SPRINGDATAJPA Core technical topic detailed explanation.
The content of this chapter has been updated to the code cloud:
Springboot Supporting Source Address: Https://gitee.com/hengboy/spring-boot-chapter
Springcloud Supporting Source Address: Https://gitee.com/hengboy/spring-cloud-chapter
Springboot related articles please visit: directory: Springboot Learning Catalogue
QUERYDSL related articles please visit: QUERYDSL General Query Framework Learning Directory
SPRINGDATAJPA related articles please visit: directory: SPRINGDATAJPA Learning Catalogue
Springboot related articles please visit: Catalogue: Springboot Learning Catalogue, thanks for reading!
Springboot Combat SPRINGDATAJPA