In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use the resultMap function in Mybatis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand it.
Preface
In Mybatis, there is a powerful functional element, resultMap. When we want to convert the data in JDBC ResultSets into reasonable Java objects, you can feel its extraordinary. As its official statement goes:
The resultMap element is the most important and powerful element in MyBatis. It frees you from 90% of the JDBC ResultSets data extraction code and in some cases allows you to do something that JDBC does not support. In fact, when writing mapping code for complex statements such as joins, a resultMap can replace thousands of lines of code that does the same thing. The design idea of ResultMap is that there is no need to configure explicit result mappings at all for simple statements, but only to describe their relationships for more complex statements.
First, field mapping
In Mybatis, the simplest way to map results is through the type alias typeAliases.
If you want to do this, the first step is to configure the path to the entity class package:
Mybatis.type-aliases-package=com.xxx.entity
All classes under this path will be registered with the TYPE_ALIASES container. When we specify the return value type, we can just use the alias.
For example, we have a User class:
@ Datapublic class User {private String id; private String username; private String password; private String address; private String email;}
If the field of the table in the database matches the property name of the User class, we can use resultType to return it.
SELECTu.id,u.username,u.password,u.address,u.emailFROMUSER u
Of course, this is an ideal situation where both the property and the field name are exactly the same. But in fact, there are inconsistencies, and at this time our resultMap is about to debut.
If the User class remains the same, but the SQL statement changes, change id to uid.
SELECTu.id as uid,u.username,u.password,u.address,u.emailFROMUSER u
Then, in the result set, we will lose id data. At this point we can define a resultMap to map different fields.
Then, we change the resultType in the above select statement to resultMap= "getUserByIdMap".
Where column corresponds to the column name or alias of the database; property corresponds to the fields or properties of the result set.
This is the simplest and most basic use of resultMap: field mapping.
Next, let's look at how several other tags are applied.
The element name description constructor is used to inject the result into the constructor when instantiating a class, association associating an object collection associating multiple objects
2. Construction method
If you want to inject the result into the constructor, you can use the constructor element.
For example, our User class adds a constructor:
Public User (String id, String name) {this.id = id+ "-"; this.username = name+ "-";}
We need to define the constructor element in resultMap:
Where column represents the database field name or alias; name is the parameter name in the constructor; and javaType specifies the type of the parameter.
As you might expect, after specifying the constructor in this way, both the id and username properties in our result set will change.
{"id": "1001 -", "username": "Hou Yi -", "password": "123456", "address": "Haidian District of Beijing", "email": "510273027@qq.com"}
III. Relevance
In the actual business, our users usually have a role. Then it is generally expressed as an entity class in the User class.
@ Datapublic class User {/ / omit user attributes. / / role information private Role role;}
When we query a user, if we also want to see its role information, we will write the query statement like this:
SELECT u.id, u.username, u.password, u.address, u.email, r.id as' role_id', r.name as' role_name' FROM USER u LEFT JOIN user_roles ur ON u.id = ur.user_id LEFT JOIN role r ON r.id = ur.role_id where u.id=# {id}
As above, you need to query the individual user and the role information of the user. But here, we can't return it with resultType=User.
After all, there is only one Role object in the User class, and there are no role_id and role_name field properties.
So, we're going to use association to associate them.
Finally, we can display the role information together:
{"id": "1001", "username": "Hou Yi", "password": "123456", "address": "Beijing Haidian District", "email": "510273027@qq.com", "role": {"id": "3", "name": "Sagittarius"}}
In fact, if you are sure that the association information is one-to-one, there is an easier way to replace association. We will see how it is implemented in the fifth part of this article, which automatically populates the association object.
IV. Collection
1. Nested result mapping of sets
Above we see a user Hou Yi whose role is Sagittarius, but most of the time, it is impossible for each of us to have only one role. Therefore, we need to change the type of the role attribute in the User class to List.
@ Datapublic class User {/ / omit user attributes. / / role information private List roles;}
Now one user corresponds to multiple roles, so it's not a simple association.
Because association is dealing with one type of association; here we have multiple types of association, so we need to use the collection attribute.
Our overall resultMap will look like this:
In this way, even if you have multiple characters, it can be displayed correctly:
{"id": "1003", "username": "Diao Chan", "password": "123456", "address": "Dongcheng District of Beijing", "email": "510273027@qq.com", "roles": [{"id": "1", "name": "Zhongdan"}, {"id": "2", "name": "wild"}]}
2. Nested Select queries for collections
In most business systems, we have a list of menus, such as a Menu table like this:
Idnameurlparent_id1 system management
01001 user Management / user11002 role Management / role11003 Unit Management / employer12 platform Monitoring
02001 system Monitoring / system/monitor22002 data Monitoring / data/monitor2
Here we divide the menu into two levels. When we return the menu to the front end, it also needs to be graded, and it is impossible to display these seven pieces of data horizontally. So, our Menu entity class here is as follows:
@ Datapublic class Menu {private String id; private String name; private String url; private String parent_id; private List childMenu;}
The first-level menu, which contains a list of second-level menus, is represented here by childMenu.
In the SQL statement, if there is no parent_id field attribute, we will first check all the first-level menus:
SELECTm.id,m.name,m.url,m.parent_idFROMm_menu mwhere 1=1and m.parent_id = # {parent_id} and m.parent_id ='0'
In this query statement, we will get two first-level menu data without transferring any parameters.
So how do you query all the menu information and display it hierarchically when you only call this method once?
Let's look at the definition of menusMap:
Let's focus on the collection element:
Property= "childMenu" corresponds to a list of child menus in the menu.
OfType= "Menu" corresponds to the type of data returned
Select= "getMenus" specifies the id of the SELECT statement
Column= "{parent_id=id}" is the expression of the parameter.
The meaning of the collection as a whole can be understood as follows:
Get the result of the childMenu attribute in the first-level menu through the SELECT statement getMenus; in the above SELECT statement, you need to pass a parent_id parameter; the value of this parameter is the id in the first-level menu.
In this way, we can get all the menu information that has been rated.
[{"id": "1", "name": "system Management", "parent_id": "0", "childMenu": [{"id": "1001", "name": "user Management", "url": "/ user", "parent_id": "1"}, {"id": "1002", "name": "role Management", "url": "/ role" "parent_id": "1"}, {"id": "1003", "name": "Unit Management", "url": "/ employer", "parent_id": "1"}}, {"id": "2", "name": "platform Monitoring", "parent_id": "0", "childMenu": [{"id": "2001" "name": "system Monitoring", "url": "/ system/monitor", "parent_id": "2"}, {"id": "2002", "name": "data Monitoring", "url": "/ data/monitor", "parent_id": "2"}]]
5. Automatically populate associated objects
We know that when Mybatis parses the return value.
The first step is to get the return value type, get the Class object, then get the constructor, set the accessibility and return the instance, and then wrap it as a MetaObject object.
After getting the results from the database rs, MetaObject.setValue (String name, Object value) is called to populate the object.
In the process, it is interesting that it will be. To separate the name attribute.
If the name property contains. The symbol will be found. The name of the attribute before the symbol, which is treated as an entity object.
Perhaps the author's description here is not intuitive enough, let's look at the example.
In the third part of this article, we have an example of a user corresponding to a role.
The User class is defined as follows:
@ Datapublic class User {/ / omit user attributes. / / role information private Role role;}
Here, we don't need to define resultMap, just return resultType=User. However, you need to change the alias of the role message, the key point is. Symbol
SELECTu.id,u.username,u.password,u.address,u.email,r.id as' role.id',r.name as' role.name'FROMUSER uLEFT JOIN user_roles ur ON u.id = ur.user_idLEFT JOIN role r ON r.id = ur.role_id
In this way, when the Mybatis resolves to the role.id property, with. After symbol separation, it is found that the role alias corresponds to the Role object, then the Role object is initialized and the value is assigned to the id property.
The related code is shown in the figure:
Thank you for reading this article carefully. I hope the article "how to use resultMap in Mybatis" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.