mybatis--Resolving conflicts where field names differ from entity class property names

Source: Internet
Author: User



Original: http://www.cnblogs.com/xdp-gacl/p/4264425.html



In peacetime development, the property names of the field names and tables in our table are not necessarily identical, and the following shows how to resolve conflicts where field names differ from entity class property names.


First, prepare to demonstrate the tables and data that need to be used
CREATE TABLEOrders (order_idINT PRIMARY KEYauto_increment, Order_noVARCHAR( -), Order_priceFLOAT);INSERT  intoOrders (Order_no, Order_price)VALUES('AAAA', at);INSERT  intoOrders (Order_no, Order_price)VALUES('bbbb', -);INSERT  intoOrders (Order_no, Order_price)VALUES('', A);
Ii. Definition of entity classes
 PackageMe.gacl.domain;/** * @authorGaCl * Defines the entity classes corresponding to the Orders table*/ Public classOrder {/*** CREATE TABLE orders (order_id INT PRIMARY KEY auto_increment, Order_no VARCHAR), O     Rder_price FLOAT); */ //The property name in the order entity class is not the same as the field name in the Orders table Private intId//id===>order_id PrivateString OrderNo;//Orderno===>order_no Private floatPrice//Price===>order_price  Public intgetId () {returnID; }  Public voidSetId (intID) { This. ID =ID; }  PublicString Getorderno () {returnOrderNo; }  Public voidSetorderno (String orderno) { This. OrderNo =OrderNo; }  Public floatGetPrice () {returnPrice ; }  Public voidSetprice (floatPrice ) {  This. Price =Price ; } @Override PublicString toString () {return"Order [id=" + ID + ", orderno=" + OrderNo + ", price=" + price+ "]"; }}




Third, write the test code 3.1, write the SQL XML mapping file


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


<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "><!--specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql the map file name so that the namespace value is guaranteed to be unique, such as namespace= " Me.gacl.mapping.orderMapper "is me.gacl.mapping (package name) +ordermapper (ordermapper.xml file removal suffix) -<Mappernamespace= "Me.gacl.mapping.orderMapper"> <!--according to the ID query to get an order object, using this query is not the result we want to query, mainly because the entity class property name and database field name does not correspond to the reason, so can not query out the corresponding record - <SelectID= "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, the use of this query can be normal query to the results we want, because we will query the field name of a and entity class property names of the same alias, so that the entity class property names and query results of the field names can be corresponding  - <SelectID= "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 have <resultMap> mapping entity class Property name and table field name one by one correspondence relationship - <SelectID= "Selectorderresultmap"ParameterType= "int"Resultmap= "Orderresultmap">SELECT * FROM Orders where Order_id=#{id}</Select> <!--mapping entity class Property names and table field names by <resultMap> - <Resultmaptype= "Me.gacl.domain.Order"ID= "Orderresultmap"> <!--to map the primary key field with the id attribute - <ID Property= "id"column= "order_id"/> <!--to map a non-primary key field with the result property - <result Property= "OrderNo"column= "Order_no"/> <result Property= "Price"column= "Order_price"/> </Resultmap> </Mapper>


2. Registering the Ordermapper.xml mapping file in the Conf.xml file


< mappers > <!-- register Ordermapper.xml file,         Ordermapper.xml is located under Me.gacl.mapping This package, so resource written me/gacl/mapping/ordermapper.xml  - <resource = "Me/gacl/mapping/ordermapper.xml"  /></mappers>
3.2. Write unit Test Code
 Packageme.gacl.test;ImportMe.gacl.domain.Order;ImportMe.gacl.util.MyBatisUtil;Importorg.apache.ibatis.session.SqlSession;Importorg.junit.Test; Public classTest2 {@Test Public voidTestgetorderbyid () {sqlsession sqlsession=mybatisutil.getsqlsession (); /*** Mapped SQL identification string, * Me.gacl.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * Geto Rderbyid is the id attribute value of the select tag, and the value of the id attribute of the SELECT tag can be used to find the SQL to execute*/String Statement= "Me.gacl.mapping.orderMapper.getOrderById";//identity string for mapping SQL//performs a query operation to automatically encapsulate the query results into an order object to returnOrder order = Sqlsession.selectone (statement,1);//query for records with ID 1 in the Orders table//you need to close sqlsession after executing SQL with sqlsessionSqlsession.close (); SYSTEM.OUT.PRINTLN (order);//print Result: null, that is, no corresponding record is queried} @Test Public voidtestGetOrderById2 () {sqlsession sqlsession=mybatisutil.getsqlsession (); /*** Mapped SQL identification string, * Me.gacl.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * Sele Ctorder is the id attribute value of the select tag, and the value of the id attribute of the SELECT tag can be used to find the SQL to execute*/String Statement= "Me.gacl.mapping.orderMapper.selectOrder";//identity string for mapping SQL//performs a query operation to automatically encapsulate the query results into an order object to returnOrder order = Sqlsession.selectone (statement,1);//query for records with ID 1 in the Orders table//you need to close sqlsession after executing SQL with sqlsessionSqlsession.close (); SYSTEM.OUT.PRINTLN (order);//Print Result: Order [id=1, ORDERNO=AAAA, price=23.0]} @Test Public voidtestGetOrderById3 () {sqlsession sqlsession=mybatisutil.getsqlsession (); /*** Mapped SQL identification string, * Me.gacl.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * Sele CTORDERRESULTMAP is the id attribute value of the select tag, and the value of the id attribute of the SELECT tag can be used to find the SQL to execute*/String Statement= "Me.gacl.mapping.orderMapper.selectOrderResultMap";//identity string for mapping SQL//performs a query operation to automatically encapsulate the query results into an order object to returnOrder order = Sqlsession.selectone (statement,1);//query for records with ID 1 in the Orders table//you need to close sqlsession after executing SQL with sqlsessionSqlsession.close (); SYSTEM.OUT.PRINTLN (order);//Print Result: Order [id=1, ORDERNO=AAAA, price=23.0] }}


Perform the results of unit tests:



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 the attribute names in the entity class are inconsistent with the field names in the table, the query operation with MyBatis cannot be queried for the corresponding results and the two approaches to the problem are as follows:



Workaround One through the query in the SQL The alias of the field name is defined in the statement so that the alias of the field name and the attribute name of the entity class match, so that the table's field name corresponds to the attribute name one by one of the entity class, which is done by defining the alias in the SQL statement to resolve the mapping of the field name and the property name.



Solution Two through <resultMap> to map the one by one correspondence between field names and entity class property names. This approach uses the workaround provided by MyBatis to resolve the mapping of field names and property names.






mybatis--Resolving conflicts where field names differ from entity class property names


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.