In the spring framework, there are different ways to get data from a data table, when the data query is relatively simple, you can inherit jparepository<t, l> use the findby*** method, by analyzing the method name to implement the query, T represents the entity that corresponds to the data table being queried, and L represents the type of the entity's primary key, such as long. about how the FindBy method through the analysis method name to realize the query, the online material is many, does not repeat.
If the query data is complex and the query conditions are more complex, consider using the JPA @query method to implement the query. The following is a brief description of how to use the method:
1. First the DAO layer inherits Repository<t, L>,t is the entity name, and L is the primary key type of the entity.
2. Write the Query method and use @query to annotate, for example:
@query (select u from the User u where name=?1 and age=?2) List Finduser (String name,int age);
Here, user is the entity name, and the name value in the parameter can be assigned to the location of the. 1 at execution time.
However, in fact, if you just get the data from a single data table, using the findby** method described above, you do not need to use @query.
However, when the query conditions are complex and you cannot use the FindBy method, you can consider using @query. First give an example:
@Query ("Select Max" (jobinfo.processes) from Jobinfo jobinfo,taskinfo TaskInfo where Taskinfo.jobid=jobinfo.id and ( Shenweistatus=4 or shenweistatus=5) and queuename=?1 ") List findmaxnuclear (String queuename);
Through this statement, you can see that it involves two entities, the query is Max, with FindBy is not possible, but this example can be very well implemented. And about 1 in the T is not much significance, should be casually write a statement of the entity involved.
Other complex queries can be implemented in this way.
Let's look at the following example:
@Query ("Select Jobinfo.queuename from Jobinfo jobinfo,taskinfo taskinfo where Taskinfo.jobid=jobinfo.id and ( Shenweistatus=1 or shenweistatus=3) and jobinfo.queuename like? 1 GROUP by Jobinfo.queuename ") List Findqueuenamebyname ( String name);
In the inside of the fuzzy query, in SQL, fuzzy query should be like '%aa% ' and other forms, but the note here if added, will error, how to solve it? You can call this method artificially to pass in the%, such as findqueuenamebyname ("%" +name+ "%"), so that the fuzzy query can be implemented.
Note that, I test found that this method can only query a field, if you want to query multiple fields, can only write multiple methods, get multiple lists, and finally put the query results into a piece. (as to whether you can query more than one field at a time, you are exploring ....) )