In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
SpringDataJpa four query methods are what, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
This article mainly introduces the detailed explanation of the four query methods of Spring Data Jpa, which is introduced in great detail through the sample code, which has a certain reference value for everyone's study or work. Friends who need it can refer to it.
First, the way to call the interface
1. Basic introduction
By calling the method in the interface to query, we need our custom interface to inherit the interface specified by Spring Data Jpa.
Public interface UserDao extends JpaRepository, JpaSpecificationExecutor
The premise of using these methods is that the entity class you define must be annotated accordingly.
@ Entity / / tag this is an entity class @ Table (name = "tbl_user") / / establish the mapping relationship between the entity class and the table public class User {@ Id / / declare this attribute as the primary key @ GeneratedValue (strategy = GenerationType.IDENTITY) / / primary key generation policy, add @ Column (name = "user_id") / / specify the column name private Integer userId; @ Column (name = "user_name") private String userName of the database table corresponding to the attribute @ Column (name = "user_address") private String userAddress; @ Column (name = "user_salary") private Double userSalary; / /... getter setter toString method}
JpaRepository
The first interface defines some simple CRUD methods. Generic T is the type of entity class you define, and generic ID is the type of primary key in your entity class.
JpaSpecificationExecutor
This interface can help us complete some complex queries. Generic T is the type of entity class you define.
two。 Usage
You only need to write your own interface to inherit the above two interfaces and fill in the generics to call the
/ / Test class, call the findAll method of the interface @ Testpublic void testFindAll () {List users = userDao.findAll (); for (User user: users) {System.out.println (user);}}
3. Matters needing attention
There are findOne () and getOne () methods in the JpaRepository interface. Literally, both methods query one, which is true, but there are some differences between them in essence.
FindOne ()
The bottom layer calls the find () method, and when we call this method, we directly find out the results for us.
GetOne ()
The bottom layer calls the getReference () method, which is a lazy loading mode, and uses dynamic proxy to create a dynamic proxy object for us. When we call the query results, we will send sql statements to query the results we need.
2. Jpql query
1. Basic introduction
Jpql is Jpa Query Language
Jpql syntax is more or less the same as sql. Jpql operates on entity classes, while sql operates directly on database tables, so jpql only replaces database table names, column names and other information in sql with entity class attributes.
For example
Query of sql statement: select * from tbl_user where user_name =?
Query for jpql statement: from User where userName =?
two。 Usage
For the custom method, we use @ Query annotation here. Value is the jpql statement. You may have noticed that each question mark is followed by a number, which actually indicates the location of the parameter in the method corresponding to this attribute, so that we can not assign values in the order of the attributes.
/ * * query * @ return user object * / @ Query (value = "from User where userId =? 2 and userName =? 1") User findUserByIdAndName (String name, int id) based on user id and name
Test code
@ Testpublic void testJpql1 () {User user = userDao.findUserByIdAndName ("Zhang San", 1); System.out.println (user);}
3. Matters needing attention
The prerequisite for using jpql is that you have configured the entity class and parameters using annotations
The details of the comments are as follows:
/ * * @ Entity * function: specifies that the current class is an entity class. The role of * @ Table *: specify the correspondence between entity classes and tables. * attribute: * name: specify the name of the database table * @ Id * function: specify that the current field is the primary key. * @ GeneratedValue * function: specify how the primary key is generated. * attribute: * strategy: specify the primary key generation policy. * GenerationType.IDENTITY: self-increment, the underlying database must support mysql * GenerationType.SEQUENCE: sequence, and the underlying database must support sequence (oracle) * a strategy provided by GenerationType.TABLE:jpa to achieve self-increment of primary keys by generating a table This table stores the value of the next added primary key * GenerationType.AUTO: a policy automatically selected by the program * * @ Column * function: specify the corresponding relationship between the entity class attribute and the database table * attribute: * name: specify the column name of the database table. * unique: whether it is unique * nullable: whether it can be empty * inserttable: whether you can insert * updateable: whether you can update * columnDefinition: define the DDL * secondaryTable that this column is created when the table is created: from the table name. If this column is not built on the master table (default is on the master table), this attribute defines the name of the slave table where the column resides and builds the development environment [key] * /
3. Sql query
1. Basic introduction
Query using SQL statement
two。 Usage
Custom method, unlike jpql, which requires nativeQuery=true to declare that this is a local query (sql query)
/ * * use sql for conditional query * / @ Query (value = "select * from tbl_user where user_name like?", nativeQuery = true) List sqlFindByName (String name)
Testing method
@ Testpublic void testSql2 () {List users = userDao.sqlFindByName ("% Zhang%"); for (User user: users) {System.out.println (user);}}
Fourth, query method naming rules
1. Basic introduction
As the name implies, this method uses the method name specified by Spring Data JPA to query. In this way, we do not need to write jpql or sql,Spring Data JPA will parse the method name to help us create the query automatically.
two。 Usage
Custom method
/ * * match query * @ param name * @ param id * @ return * / List findUserByUserNameLikeAndUserId (String name, int id) based on user name fuzzy query and id
test
@ Testpublic void TestName1 () {List users = userDao.findUserByUserNameLikeAndUserAddress ("% Zhang%", "Beijing"); for (User user: users) {System.out.println (user);}}
3. Naming rules
According to the rules defined by Spring Data JPA, the query method starts with findBy and the delete method begins with deleteBy. When it comes to conditional queries, the attributes of the condition are connected with conditional keywords, and it should be noted that the first letter of the conditional attribute should be capitalized. When parsing the method name, the framework will first truncate the extra prefix of the method name, and then parse the rest.
If you are using an idea compiler, idea will also give you a hint when you write it.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.