Use the queryformap method of ibatis to compare the resultclass and resultmap

Source: Internet
Author: User

Ibatis return value parameter types include resultmap and resultclass.

The two types of options can be described in two sentences:

1. When the name of the result set column corresponds to the attribute name of the class, you can directly use resultclass to specify the query result type.

2. When the query result set does not match the attribute name, you can use resultmap to specify the ing between the column name and the object attribute name. Otherwise, the non- ing attribute is null or 0.

The purpose of the resultmap ing result is to bind the query result set to the attributes of the ing object. In fact, resultclass can be used to solve this problem,
In the SQL statement, use the as rename method to rename fields in the result set that are different from the object property name.

There is an interesting example for resultmap and resultclass:

The ibatis query method has the following query method:

For the time being, let's not talk about what this method is. If we have such a requirement, there are many pieces of data in the database, one field, if it is name, each piece of data maps to one object.

We need to query all the data and perform different processing based on different name attribute values.

The first thing to think of is to first query all the data, instead of repeatedly querying all the data based on different names. There are also two ways to query all the data,

First, we usually use the list <?> Set form, another map <?,?> .

In this case, it is obvious that the map is directly queried <?,?> In this way, we can find the corresponding object in the program based on the known name without having to traverse it cyclically.

There may not be many such requirements. Let's talk about it.

The first method:
Public java. util. Map queryformap (Java. Lang. String ID,
Java. Lang. Object parameterobject,
Java. Lang. String keyprop) throws java. SQL. sqlexception

This method has three parameters: Statement, input parameter query, and key attribute of the returned map set.

Public Map <string, user> getusermap2 () throws sqlexception
{
Return sqlmapclient. queryformap ("user. queryformap2", null, "userid ");
}

There are two methods in Dao. The first function is to query all user objects and store the userid of the user object as the key in the map set to return.

 

XML ing file:
<Select id = "queryformap2" resultclass = "Java. util. hashmap"> // note that Java. util. map cannot be written here and must be a specific implementation class. Otherwise, ibatis cannot be instantiated.
Select * From t_user
</SELECT>

Test code:
Map <string, user> User = Dao. getusermap2 ();
System. Out. println (User );

Query map results:
{Null = {age = 28, userid = 6, username = zhangbo} // The output result is very strange. There are six pieces of data in the database. why only the last one is queried, and the key is null.

Value is not a user object. The user object does not have the username attribute. {age = 28, userid = 6, username = zhangbo} is only a piece of data in the database.
Map <string, user> User = Dao. getusermap2 ();
System. Out. println (User );

User user2 = user. Get (null );
// Try to get the user object whose key is null from the map and throw the type conversion exception. That is, the user object in the map is not a user object because the user object does not have the username attribute at all.
System. Out. println (user2.getname ());

Set to write the user in Map <string, user> to any type. That is:
Map <string, string> User = Dao. getusermap2 ();
System. Out. println (User );
The execution output result is the same as the output result.
 
Why? In fact, the bottom layer of ibatis does not know that I have a user-type object. How does it map database data?
In fact, you can understand whether the key is null as follows:
Return sqlmapclient. queryformap ("user. queryformap2", null, "userid") Written in Dao ");
The key of the map set is named "userid". I want to use the "userid" of the user object as the key, but ibatis does not know what the user object is. The ing File
There is no user object in it, because the resultclass specified by the ing file is Java. util. hashmap, where the userid attribute exists.
You can understand that only the last number of queried data is as follows:
The queryformap () method of ibatis first queries a list set based on conditions, then traverses the list set, and stores the object in the form of key and value into the map to return.
In fact, the list set does query the six data entries that meet the conditions of the database, but the keys specified for the six data entries are all null. During traversal, the first entry in the list is null in the form of key.
Store the second record in map and put the second record in map with the key as null. Obviously, the key is the same, which is equivalent to replacing the first record, and so on. In map, only the last record of data is allowed.

I cannot say why the key is null at the moment. Awaiting research! The root cause is that resultclass is used, and hashmap does not have the "userid" attribute ???
 
Let's try using resultmap and specify attributes for hashmap:
<Resultmap class = "Java. util. hashmap" id = "resultMap-UserMap2">
<Result property = "userid" column = "userid"/>
<Result property = "username" column = "username"/>
<Result property = "userage" column = "Age"/>
</Resultmap>
<Select id = "queryformap2" parameterclass = "Java. Lang. String" resultmap = "resultMap-UserMap2">
Select * From t_user
</SELECT>
 
Public Map <string, user> getusermap2 () throws sqlexception
{
Return sqlmapclient. queryformap ("user. queryformap2", null, "userid ");
}
In this way, we specify the ing between database fields and object objects. Let's take a look at the execution result:
{
3 = {userid = 3, username = zhangbo, userage = 25 },

5 = {userid = 5, username = zhangbo, userage = 27 },
2 = {userid = 2, username = zhangbo, userage = 24 },
4 = {userid = 4, username = zhangbo, userage = 26 },
6 = {userid = 6, username = zhangbo, userage = 28 },
1 = {userid = 1, username = zhangbo, userage = 23}
}
The output results seem to be correct. There are two questions: why is the order disordered? Is value really the user object in Map <string, user>?
Map <string, user> User = Dao. getusermap2 ();
System. Out. println (User );
User user2 = user. Get ("3"); // throwing a type conversion exception, that is, the map object is not a user object, because the user object does not have the username attribute at all.
System. Out. println (user2.getname ());
 
Is there any type conversion exception if we map the database fields to the three attributes of the user in the resultmap XML?
Try:
<Resultmap class = "Java. util. hashmap" id = "resultMap-UserMap2">

<Result property = "userid" column = "userid"/>
<Result property = "name" column = "username"/>
<Result property = "Age" column = "Age"/>
</Resultmap>
<Select id = "queryformap2" parameterclass = "Java. Lang. String" resultmap = "resultMap-UserMap2">
Select * From t_user
</SELECT>
 
Public Map <string, user> getusermap2 () throws sqlexception
{
Return sqlmapclient. queryformap ("user. queryformap2", null, "userid ");
}
 
Note: three attributes of the user object: userid, name, and age.
 
All right, the above XML ing file maps the database fields to the three attributes of the user object, and the returned resultclass is still java. util. hashmap.
Our goal is to encapsulate the data in the database into a specific user object, and then store it in map with the userid as the key and the user object as the value,
Imagine how it can be implemented? It seems yes,
1. We seem to have specified the map key in queryformap as "userid" (sqlmapclient. queryformap ("user. queryformap2", null, "userid ");).
2. We seem to have told ibatis that we need to store the user object in map, because the return value of our method is clearly written in <string, user>.

OK. Try again:
Map <string, user> User = Dao. getusermap2 ();
System. Out. println (User );
User user2 = user. Get ("3"); // or throw type conversion exception.
An error occurred while trying to convert the objects in the Map <object, Object> set that ibatis gave to us into users. Therefore, the objects in the map returned by ibatis
Why is it not a user object?
What exactly is it?
Unveil its mysterious veil:
Since we don't know what the object in map is, let's change the return value of DAO method to map <object, Object>.
Map <object, Object> map = Dao. getusermap2 ();
System. Out. println (Map. getclass (). getname (); // This must be of the Java. util. hashmap type.
 
System. Out. println (Map. Get ("1"). getclass (). getname (); // This is actually of the Java. util. hashmap type,
The above results show that the query result is a hashmap set with the specified "userid" as the key and hashmap as the value in the map.
How to explain it?
From the beginning to the end, there is always something wrong, because we have never told ibatis that we want to return the user object, because our resultclass is Java. util. hashmap
Although the returned value of our method is Map <string, user>, the actual returned value is Map <object, Object>.
The Return Value of the method returns all types of Map sets can be compiled, and any type in Java is the child type of the object, which is just an illusion.
User user2 = user. Get ("3"); when we really want to convert the object type to the user type, an error is reported. The conversion from hashmap to user is obvious.

From this point of view, ibatis is flexible. We can use queryformap to specify the key in the map,
Return sqlmapclient. queryformap ("user. queryformap2", null, "XXX ");
If we want to return the Map <object, Map <> form, it is not required to be written as "userid", it is just a form parameter, as long
You can use the same property. Of course, the database field value corresponding to this property will be treated as the key.
<Resultmap class = "Java. util. hashmap" id = "resultMap-UserMap2">
<Result property = "XXX" column = "userid"/>
<Result property = "name" column = "username"/>
<Result property = "Age" column = "Age"/>
</Resultmap>
What if the specified key is repeated in the database? For example:
<Resultmap class = "Java. util. hashmap" id = "resultMap-UserMap2">
<Result property = "XXX" column = "userid"/>
<Result property = "ooo" column = "username"/>
<Result property = "Age" column = "Age"/>
</Resultmap>
Return sqlmapclient. queryformap ("user. queryformap2", null, "ooo"); // use the database username field value as the key
As expected, the result is:
{Zhangbo = {age = 28, xxx = 6, OOO = zhangbo. We can see that
The "property" in the resultmap file is the key value of the map in our map <object, Map <>.

In this way, ibatis is flexible and corresponds to a database table. I want to use ibatis for addition, deletion, and query, especially for queries. We do not have to need an object and
The table results correspond to each other. We can still encapsulate the data in the table into map for convenient use.
 
Then, according to our original intention, we put an object in map, and put a property of this object as the key, and the object as the value in map to return the result,
The answer is very positive. Yes. Make a slight modification:
 
Complete ing file:
<Resultmap class = "com. ibatis. entity. User" id = "resultMap-UserMap2">
<Result property = "userid" column = "userid"/> // you can specify the ing between each attribute of a user and a database field.
<Result property = "name" column = "username"/>
<Result property = "Age" column = "Age"/>
</Resultmap>
<Select id = "queryformap2" parameterclass = "Java. Lang. String" resultmap = "resultMap-UserMap2">
Select * From t_user
</SELECT>
Complete Dao code:
@ Suppresswarnings ("unchecked ")
Public Map <string, user> getusermap2 () throws sqlexception
{

 

Return sqlmapclient. queryformap ("user. queryformap2", null, "userid"); // The specified key name must be an attribute name of the user.
}
Complete Test code:
Map <string, user> User = Dao. getusermap2 ();

System. Out. println (User );
System. Out. println (user. Get ("1"). getname ());
Complete output result:
{
3 = User: age = 25 & userid = 3 & name = zhangbo,
5 = User: age = 27 & userid = 5 & name = zhangbo,
2 = User: age = 24 & userid = 2 & name = zhangbo,
4 = User: age = 26 & userid = 4 & name = zhangbo,
6 = User: age = 28 & userid = 6 & name = zhangbo,
1 = User: age = 23 & userid = 1 & name = zhangbo
}
Zhangbo

To achieve this, the resultclass in our resultmap should be a specific object, rather than Java. util. hashmap.

There is also a method to rewrite the queryformap method.
Public java. util. Map queryformap (Java. Lang. String ID,
Java. Lang. Object parameterobject,
Java. Lang. String keyprop,
Java. Lang. String valueprop)

This method not only specifies the key in the returned map, but also specifies the value in the map. By using this method, we can query the specific two field values in a table.
The value of a field is used as the key, and the value of a field is used as the value.
For example:

Complete Dao code:
@ Suppresswarnings ("unchecked ")
Public Map <string, string> getusermap3 (string userid) throws sqlexception
{
// Similarly, "XXX" and "ooo" are only form parameters and any string
Return sqlmapclient. queryformap ("user. queryformap3 ", userid," XXX "," ooo "); // you can call this operation to query a data entry of a specified userid, only the resultmap ing fields can be controlled.
}
 
Resultmap ing file:
<Resultmap class = "Java. util. hashmap" id = "resultMap-UserMap3">

<Result property = "XXX" column = "username"/> // specifies the name of the database field corresponding to XXX and ooo. Which field value of the database is used as the key and which value is used as the value.
<Result property = "ooo" column = "Age"/>
</Resultmap>
<Select id = "queryformap3" parameterclass = "Java. Lang. String" resultmap = "resultMap-UserMap3">
Select * From t_user where userid = # AAA # // "AAA" is also a form parameter, any string
</SELECT>
 
Test code:
Map <string, string> map = Dao. getusermap3 ("3 ");
System. Out. println (MAP );
 
Output result:
{Zhangbo = 25}
 
Note the following:
<Select id = "queryformap3" parameterclass = "Java. Lang. String" resultclass = "Java. util. hashmap"> // can I directly write hashmap here?
Select * From t_user where userid = # AAA #
</SELECT>
Return sqlmapclient. queryformap ("user. queryformap3", userid, "XXX", "ooo"); // assume that "XXX" and "ooo" are the names of two fields in the database.

Because we know that when the object property name is the same as the data field, we can directly write resultclass = "XXX. XXX. XXX", only when our database
When the field name is different from the object property, we need a resultmap to match the database field with the object property name.
 
Even so, the above assumptions are not acceptable. In this case, you must use resultmap to specify the key and value of the hashmap corresponding to the database field. In fact, it is quite understandable,
1. If you directly specify it as resultclass = "Java. util. hashmap", hashmap does not have a property called "XXX", "ooo", so ibatis cannot be used with common objects.
Similarly, database fields are automatically mapped to attributes with the same object name.
2. The resultmap here does not specify the attribute of the database field corresponding to the object, but specifies the database field as the key and the field as the value. So which one?
Which value is specified when queryformap is called as the key.

Summary:
For the first queryformap method that only specifies the key:
If resultclass = "Java. util. hashmap". ibatis is still set in resultmap
The key value specified by the database is used as the key, and all fields are encapsulated into hashmap as the value of the returned map. When all fields are converted to hashmap
And the field value of the database as the value.
If resultclass = "specific object" is set, ibatis sets the database field value to the specified attribute of the object as the value, and the key is still
Attribute.
The queryformap method for the second specified key and value:
Queries any two Field Values in the database. One is the key that returns the map, and the other is the value that returns the map.
Together with resultmap, resultclass = "Java. util. hashmap" in resultmap ".
 
The two methods show that the resultclass and resultmap of ibatis are very flexible and useful, although the queryformap method may not be used much in specific work,
However, the existence of these two methods makes ibatis more powerful, and database operations do not have to be associated with a certain object model. With Java hashmap
This can be done. From this point of view, hashmap has a striking similarity with a pojo object. Let's take a look.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.