MyBatis Learning Tutorial (iv)-How to quickly resolve conflict issues where field names are not the same as entity class property names _java

Source: Internet
Author: User
Tags sql using

In the development of the project, we often encounter the field names in the table and the corresponding entity class property names are not necessarily exactly the same situation, the following small series to show you how to resolve the field name and entity class Property name is not the same conflict problem, interested friends to study together.

Preparation of tables and data to be used for presentation

CREATE TABLE orders (
order_id INT PRIMARY KEY auto_increment,
order_no VARCHAR), 
order_price FLOAT
);
INSERT into orders (Order_no, Order_price) VALUES (' aaaa ',);
INSERT into orders (Order_no, Order_price) VALUES (' bbbb ', 33);

Ii. Defining entity Classes

Package me.gacl.domain;
/**
* @author gacl
* defines the entity class corresponding to the Orders table
/public class Order {
/**
* 
CREATE TABLE orders (
order_id INT PRIMARY KEY auto_increment,
order_no VARCHAR (), 
order_price FLOAT
);
*///order entity class The name of the
property and the field name in the Orders table are not the same as the
private int id;//id===>order_id
private String orderNo; Orderno===>order_no
Private float price//price===>order_price public
int getId () {return
id;< c20/>} public
void setId (int id) {
this.id = ID;
}
Public String Getorderno () {return
orderNo;
}
public void Setorderno (String orderNo) {
This.orderno = orderNo;
}
public float GetPrice () {return price
;
}
public void Setprice (float price) {
This.price = Price;
}
@Override public
String toString () {return
"order [id= + ID +", orderno= "+ OrderNo +", price= "+ price+"] " ;
}

Third, write test code

3.1. Write SQL XML mapping file

1, create a ordermapper.xml file, the contents of Ordermapper.xml are as follows:

<?xml version= "." Encoding= "utf-"?>
<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper.//en" "Http://mybatis.org/dtd/mybatis--mapper.dtd" >
<!- -Specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql mapping file name so that the namespace value is unique,
such as namespace= " Me.gacl.mapping.orderMapper "is me.gacl.mapping (package name) +ordermapper (ordermapper.xml file removal suffix)
-->
<mapper Namespace= "Me.gacl.mapping.orderMapper" >

According to the ID query to get an order object, using this query is not the query we want the results, this is mainly because the entity class property name and the database field name does not correspond to the reason, so can not query the corresponding records

-->
<select id= "Getorderbyid" parametertype= "int" 
resulttype= "Me.gacl.domain.Order" >
SELECT * FROM orders where Order_id=#{id}
</select>

According to the ID query to get an order object, using this query can be normal query to the results we want,
This is because we will query the field name of the same as the entity class property name Alias, so that the entity class property names and query results in the field names can correspond to the

-->
<select id= "Selectorder" parametertype= "int" 
resulttype= "Me.gacl.domain.Order" >
Select order_id ID, order_no orderno,order_price price from orders where Order_id=#{id}
</select>

According to the ID query to get an order object, using this query can be normal query to the results we want, because we through the <resultMap> mapping entity class attribute names and table field name one by one correspondence-->

<select id= "Selectorderresultmap" parametertype= "int" resultmap= "Orderresultmap" >
select * FROM Orders Where Order_id=#{id}
</select>
<!--through <resultMap> mapping entity class attribute names and table field names-->
< Resultmap type= "Me.gacl.domain.Order" id= "Orderresultmap" >
<!--use the id attribute to map the primary key field--> property
= "id" column= "order_id"/>
<!--map non-primary key fields with the result property--> <result property= "orderNo" Order
_no "/>
<result property=" Price "column=" Order_price "/>
</resultMap>

2, register the Ordermapper.xml mapping file in the Conf.xml file

<mappers> 
<!--register ordermapper.xml file, 
Ordermapper.xml is located me.gacl.mapping this package, so resource written me/gacl/ mapping/ordermapper.xml-->
<mapper resource= "Me/gacl/mapping/ordermapper.xml"/>
</mappers >

3.2, write unit test code

Package me.gacl.test;
Import Me.gacl.domain.Order;
Import Me.gacl.util.MyBatisUtil;
Import org.apache.ibatis.session.SqlSession;
Import Org.junit.Test; public class Test {@Test public void Testgetorderbyid () {sqlsession sqlsession = mybatisutil.getsqlsession ();/** * Mapping sql Identity String, * Me.gacl.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * Getorderbyid is the id attribute value of the select tag, You can find the SQL/string statement = "Me.gacl.mapping.orderMapper.getOrderById" to execute by using the id attribute value of the select tag;//Map SQL Identity string//Execute query operation , the query result is automatically encapsulated into an order object returning order = Sqlsession.selectone (statement,);//Query Orders table ID for record//
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession. SYSTEM.OUT.PRINTLN (order);//print Result: null, that is, no query out the corresponding records} @Test public void Testgetorderbyid () {sqlsession sqlsession =
Mybatisutil.getsqlsession (); /** * Maps the identity string of SQL, * Me.gacl.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * The selectorder is the id attribute value of the Select label, which can be found by the ID attribute value of the select tag to execute the SQL/String statement = " Me.gacl.mapping.orderMapper.selectOrdeR/Map SQL identity string//Execute query operation, automatically encapsulate query results into order object return order = Sqlsession.selectone (statement,);//Query Orders table ID for record//
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
SYSTEM.OUT.PRINTLN (order);//Print Result: [Id=, Orderno=aaaa, price=.]} @Test public void Testgetorderbyid () {sqlsession sqlsession = mybatisutil.getsqlsession ();/** * Map SQL's identity string, * me.gacl.ma Pping.ordermapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * Selectorderresultmap is the id attribute value of the Select label.
You can find the SQL/string statement = "Me.gacl.mapping.orderMapper.selectOrderResultMap" to execute by using the id attribute value of the select tag;//Mapping SQL identity string Perform a query operation to automatically encapsulate the query results into an Order object return order = Sqlsession.selectone (statement,);//Query Orders table ID for record//
You need to close sqlsession sqlsession.close () after executing SQL using sqlsession.
SYSTEM.OUT.PRINTLN (order);//Print Result: [Id=, Orderno=aaaa, price=.]}  }

To perform the results of a unit test:

1. The Testgetorderbyid method executes the query and returns a null.

2, the TestGetOrderById2 method and the TestGetOrderById3 method can get the desired result normally after executing the query.

Iv. Summary

The test code above demonstrates that when a property name in an entity class is inconsistent with a field name in a table, the problem of the corresponding result cannot be queried when the query operation is performed using MyBatis, and the two approaches to the problem are applied:

  workaround One: by defining the alias of the field name in the query's SQL statement, the alias of the field name matches the property name of the entity class, so that the field name of the table corresponds to the property name one by one of the entity class. This is done by defining the alias in the SQL statement to resolve the mapping relationship between the field name and the property name.

  workaround two: one by one correspondence between the field name and the entity class property name is mapped by <resultMap>. This approach uses the workaround provided by MyBatis to resolve the mapping relationship between the field name and the property name.

The above is small set to introduce the MyBatis Learning Tutorial (iv)-How to quickly resolve the field name and entity class Property name is not the same as the conflict problem, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.