MyBatis Learning Summary 4--resolving conflicts where field names differ from entity class property names

Source: Internet
Author: User



In peacetime development, the field names in our table and the table corresponding entity class property names are not necessarily exactly the same, if you directly in the XML mapping file using SQL to map, will cause the return value is empty, the following elaboration of the solution:


Test the tables and data 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);
Defining entity Classes
 PackageCom.tfj.domain;/** * @authorJacksile defining the entity classes corresponding to the Orders table*/ Public classOrder {//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 + "]"; }}
Writing test Code


Write the SQL XML mapping file Ordermapper.xml, 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= " Com.tfj.mapping.orderMapper "is com.tfj.mapping (package name) +ordermapper (ordermapper.xml file removal suffix) -<Mappernamespace= "Com.tfj.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= "Com.tfj.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= "Com.tfj.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= "Com.tfj.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>


3.2, the unit test, follow-up will continue to test, no longer call the output of the way


 Packagecom.tfj.test;Importorg.apache.ibatis.session.SqlSession;Importorg.junit.Test;ImportCom.tfj.domain.Order;ImportCom.tfj.util.MyBatisUtil; Public classTest2 {@Test Public voidTestgetorderbyid () {sqlsession sqlsession=mybatisutil.getsqlsession (); /*** Mapping SQL identification String, Com.tfj.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * Getorderbyid is S The id attribute value of the elect tag, which can be found by using the id attribute value of the select tag to execute the SQL*/String Statement= "Com.tfj.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 (); /*** Mapping SQL identification String, Com.tfj.mapping.orderMapper is the value of namespace attribute of mapper tag in Ordermapper.xml file, * selectorder is SE The id attribute value of the lect tag, which can be found by using the id attribute value of the select tag to execute the SQL*/String Statement= "Com.tfj.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, Com.tfj.mapping.orderMapper is the value of the namespace attribute of the mapper tag in the Ordermapper.xml file, * selectorderres ULTMAP 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= "Com.tfj.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.


Summarize


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 Learning Summary 4--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.