This is the 8th mybatis series. Did not see the previous article to go to [Java tomb Fox] public number to view the previous article, easy to understand and master. In the last article, we introduced some ways to use mybatis query, especially one-to-one query and one-to-many query. Did not see the recommendation to the public number to check.
Today we’re going to take a look at automatic mapping that we’ve been using but haven’t talked about enough.
What is automatic mapping?
Before introducing automatic mapping, take a look at manual mapping, as follows:
<resultMap id="orderModelMap1" type="com.zhonghu.chat08.demo7.model.OrderModel"> <id column="id" property="id"/> <result column="userId" property="userId" /> <result column="createTime" property="createTime" /> <result column="upTime" property="upTime" /> </resultMap> <select id="getById1" resultMap="orderModelMap1"> <! [CDATA[ SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM orders a WHERE a.id = #{value} ]]> </select>Copy the code
Note that there are four rows of configuration in the resultMap element above, as follows:
<id column="id" property="id"/>
<result column="userId" property="userId" />
<result column="createTime" property="createTime" />
<result column="upTime" property="upTime" />
Copy the code
These four lines of code configure the mapping between the columns of the SQL result and the fields in the OrderModel object.
Mybatis supports automatic mapping. When automatic mapping is enabled, when the column name of SQL is the same as the field name of Model (case insensitive), MyBatis will perform automatic mapping internally. There is no need for us to manually write the above 4 line mapping rules.
Let’s change the above example to automatic mapping as follows:
<resultMap id="orderModelMap2" type="com.zhonghu.chat08.demo7.model.OrderModel" autoMapping="true"> </resultMap> <select id="getById2" resultMap="orderModelMap2"> <! [CDATA[ SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM orders a WHERE a.id = #{value} ]]> </select>Copy the code
Note that the autoMapping attribute in the resultMap above, whether to enable automatic mapping, we set it to true, so that Mybatis will automatically map values according to column names and fields with the same name in Model.
The above two configurations end up with the same query result, automatically assigning the values of the four fields corresponding to the query result to the property of the same name in OrderModel.
Automatic mapping switch
Automatic mapping in MyBatis mainly has two configurations. One is the global configuration, which takes effect on all the resultMap in the application. This is set in the MyBatis configuration file. Another method is to configure the resultMap autoMapping attribute.
When mybatis determines whether automatic mapping is enabled for a resultMap, it will first search for its own autoMapping attribute. If the value of this attribute is set, it will directly use the value of this attribute. If the autoMapping attribute of the resultMap element is not configured, If yes, go to the automatic mapping rule configured globally.
Let’s explain the content of this section in detail.
Mybatis automatically maps global configuration
Add the following configuration to myBatis global profile:
< Settings > <setting name="autoMappingBehavior" value=" automatic mapping rule "/> </ Settings >Copy the code
There are mainly several kinds:
- NONE: Disables global mapping
- PARTIAL: Maps attributes other than those for which nested result mappings (that is, the attributes of the connection) were defined internally. This is also the default.
- FULL: Automatically maps all attributes.
NONE
When the value of autoMappingBehavior is set to NONE in mybatis global configuration, it indicates that global automatic mapping is disabled. As a result, SQL actually returns the result, but the result is not automatically mapped, so the return is null
PARTIAL
Some complex query mappings (such as Association and Collection) are nested in the resultMap. With PARTIAL, if there is a nested mapping, the nested mapping is not automatically mapped.
FULL
Automatically map all attributes.
AutoMapping use
As mentioned above, when you specify the autoMapping attribute in a resultMap, the automatic mapping of this resultMap is controlled by the autoMapping attribute, and has nothing to do with the global mapping behavior in Mybatis.
Case 1
This core configuration is mainly in SQLMap as follows:
<resultMap id="orderModelMap7" type="com.zhonghu.chat08.demo7.model.OrderModel" autoMapping="true"> <association property="userModel" autoMapping="true"> <id column="user_id" property="id"/> </association> </resultMap> <select id="getById7" resultMap="orderModelMap7"> <! [CDATA[ SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime, b.id as user_id, b.name FROM orders a,user b WHERE a.user_id = b.id AND a.id = #{value} ]]> </select>Copy the code
Corresponding test cases
com.zhonghu.chat08.demo7.Demo7Test#getById7 @Test public void getById7() throws IOException { this.before("demo7/mybatis-config1.xml"); try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) { OrderMapper mapper = sqlSession.getMapper(OrderMapper.class); OrderModel orderModel = mapper.getById7(2); log.info("{}", orderModel); }}Copy the code
Run the output
24:37. 544. [the main] the DEBUG C.J.C.D.M apper. OrderMapper. GetById7 - = = > Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime, b.id as user_id, B. name FROM Orders a,user B WHERE a. us_id = B. id AND A. id =? 24:37.589 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById7 - ==> Parameters: 2 (Integer) 24:37) 610 [main] the DEBUG C.J.C.D.M apper. OrderMapper. GetById7 - < = = Total: 1 24:37. [the main] 610 INFO C.J.C hat05. Demo7. Demo7Test - OrderModel (id = 2, userId = 1, createTime = 1610803573, UpTime =1610803573, userModel= userModel (id=1, name= userModel)Copy the code
All properties in OrderModel are automatically mapped successfully.
Autoassembly is not that much fun, and failure can bring some pitfalls, as shown in example 2 below.
Example 2
According to the order number, query the order information, incidentally query the order details list. For this we use one to many queries in Mybatis.
OrderDetaiMapper. XML to join
<select id="getListByOrderId1" resultType="com.zhonghu.chat08.demo7.model.OrderDetailModel"> <! [CDATA[ SELECT a.id, a.order_id AS orderId, a.goods_id AS goodsId, a.num, a.total_price AS totalPrice FROM order_detail a WHERE a.order_id = #{value} ]]> </select>Copy the code
This can query the detailed list associated with the order according to the order ID.
OrderMapper. XML to join
<resultMap id="orderModelMap8" type="com.zhonghu.chat08.demo7.model.OrderModel" autoMapping="true"> <collection property="orderDetailModelList" select="com.zhonghu.chat08.demo7.mapper.OrderDetailMapper.getListByOrderId1" column="id"/> </resultMap> <select id="getById8" resultMap="orderModelMap8"> <! [CDATA[ SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM orders a WHERE a.id = #{value} ]]> </select>Copy the code
The test case
com.zhonghu.chat08.demo7.Demo7Test#getById8 @Test public void getById8() throws IOException { this.before("demo7/mybatis-config.xml"); try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) { OrderMapper mapper = sqlSession.getMapper(OrderMapper.class); OrderModel orderModel = mapper.getById8(1); log.info("{}", orderModel); }}Copy the code
Run the output
11:06. 193. [the main] the DEBUG C.J.C.D.M apper. OrderMapper. GetById8 - = = > Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM orders a WHERE a.id = ? 11:06. 229. [the main] the DEBUG C.J.C.D.M apper. OrderMapper. GetById8 - = = > the Parameters: 1 (Integer) 11:06. [the main] 250 DEBUG C.J.C.D.M.O.G etListByOrderId1 - = = = = > Preparing: SELECT a.id, a.order_id AS orderId, a.goods_id AS goodsId, a.num, a.total_price AS totalPrice FROM t_order_detail a WHERE a.order_id = ? 11:06. 251. [the main] the DEBUG C.J.C.D.M.O.G etListByOrderId1 - = = = = > the Parameters: 1 (Integer) 11:06. [the main] 255 DEBUG C.J.C.D.M.O.G etListByOrderId1 - < = = = = Total: 2 11:06. [the main] 256 DEBUG C.J.C.D.M apper. OrderMapper. GetById8 - < = = Total: 1 11:06. [the main] 256 INFO C.J.C hat05. Demo7. Demo7Test - OrderModel (id = null, userId = 2, createTime = 1610803573, upTime=1610803573, userModel=null, orderDetailModelList=[OrderDetailModel(id=1, orderId=1, goodsId=1, num=2, TotalPrice =16.00), OrderDetailModel(id=2, orderId=1, goodsId=1, num=1, totalPrice=16.00)])Copy the code
Note that the id property of OrderModel in the output is null. This is mainly the result of the following configuration
<collection property="orderDetailModelList" select="com.zhonghu.chat08.demo7.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>Copy the code
There is a column attribute in the above configuration, which specifies id. Mybatis thinks that if you manually specify the mapping relation of ID field, the automatic mapping of ID field to orderModel. id property is skipped, so the ID attribute of OrderModel object is not assigned. In orderModelMap8, we need to manually specify the mapping rule for id as follows:
<resultMap id="orderModelMap8" type="com.zhonghu.chat08.demo7.model.OrderModel" autoMapping="true">
<id column="id" property="id" />
<collection property="orderDetailModelList" select="com.zhonghu.chat08.demo7.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>
</resultMap>
Copy the code
It is normal to run the test case again.
To summarize
For our development, automatic mapping can really help us save some code, but there are some hidden dangers, we want to develop the system is robust, recommend writing mapper XML, or spend some time will mapping configuration to write up, it can eliminate some hidden dangers, to make our system more stable.
The last
- If you feel that you have gained something after watching it, I hope you can pay attention to it and give me a “like”, which will be the biggest motivation for my update. Thank you for your support
- Welcome everyone to pay attention to my public number [Java tomb Fox], focus on Java and computer basic knowledge, to ensure that you see something harvest, do not believe you hit me
- Ask for a key three even: like, forward, look.
- If you have different opinions or suggestions after reading, welcome to comment together. Thank you for your support and kindness.
I’m Tsuka Fox. I love programming as much as you do.
Please follow the public account “Java Tomb Fox” for the latest news