亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Mybatis實現自動映射

發布時間:2020-10-28 21:34:55 來源:億速云 閱讀:197 作者:Leah 欄目:開發技術

本篇文章給大家分享的是有關使用Mybatis實現自動映射,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

什么是自動映射?

介紹自動映射之前先看一下手動映射,如下:

<resultMap id="orderModelMap1" type="com.javacode2018.chat05.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
    t_order a
  WHERE
    a.id = #{value}
  ]]>
</select>

注意上面的resultMap元素中有4行配置,如下:

<id column="id" property="id"/>
<result column="userId" property="userId" />
<result column="createTime" property="createTime" />
<result column="upTime" property="upTime" />

這4行代碼用于配置sql結果的列和OrderModel對象中字段的映射關系。

大家有沒有注意到,映射規則中column和property元素的值都是一樣,mybatis中支持自動映射配置,當開啟自動映射之后,當sql的列名和Model中的字段名稱是一樣的時候(不區分大小寫),mybatis內部會進行自動映射,不需要我們手動去寫上面的4行映射規則。

下面我們將上面的示例改成自動映射的方式,如下:

<resultMap id="orderModelMap2" type="com.javacode2018.chat05.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
    t_order a
  WHERE
    a.id = #{value}
  ]]>
</select>

注意上面的resultMap中的autoMapping屬性,是否開啟自動映射,我們設置為true,這樣mybatis會自動按照列名和Model中同名的字段進行映射賦值。

上面兩個配置最后查詢結果是一樣的,都會將查詢結果對應的4個字段的值自動賦值給OrderModel中同名的屬性。

自動映射開關

mybatis中自動映射主要有2種配置,一種是全局的配置,對應用中所有的resultMap起效,這個是在mybatis配置文件中進行設置的;另外一種是通過resultMap的autoMapping屬性進行配置。

mybatis判斷某個resultMap是否開啟自動映射配置的時候,會先查找自身的autoMapping屬性,如果這個屬性設置值了,就直接用這個屬性的值,如果resultMap元素的autoMapping屬性沒有配置,則走全局配置的自動映射規則。

下面我們來詳解介紹一下這款的內容。

mybatis自動映射全局配置

在mybatis全局配置文件中加入下面配置:

<settings>
  <setting name="autoMappingBehavior" value="自動映射規則"/>
</settings>

autoMappingBehavior值來源于枚舉:org.apache.ibatis.session.AutoMappingBehavior,源碼:

public enum AutoMappingBehavior {

 /**
  * Disables auto-mapping.
  */
 NONE,

 /**
  * Will only auto-map results with no nested result mappings defined inside.
  */
 PARTIAL,

 /**
  * Will auto-map result mappings of any complexity (containing nested or otherwise).
  */
 FULL
}
  • NONE:關閉全局映射開關
  • PARTIAL:對除在內部定義了嵌套結果映射(也就是連接的屬性)以外的屬性進行映射,這個也是默認值。
  • FULL:自動映射所有屬性。

小提示:settings元素中有很多配置,這些配置最后都會被解析成org.apache.ibatis.session.Configuration的屬性,源碼位于org.apache.ibatis.builder.xml.XMLConfigBuilder#settingsElement方法中。

下面我們來演示一下autoMappingBehavior每種配置的效果。

NONE

mybatis-config.xml加入配置

<settings>
  <!-- 關閉自動映射開關 -->
  <setting name="autoMappingBehavior" value="NONE"/>
</settings>

OrderMapper.xml

<resultMap id="orderModelMap4" type="com.javacode2018.chat05.demo7.model.OrderModel">
</resultMap>

<select id="getById4" resultMap="orderModelMap4">
  <![CDATA[
  SELECT
    a.id,
    a.user_id userId,
    a.create_time createTime,
    a.up_time upTime
  FROM
    t_order a
  WHERE
    a.id = #{value}
  ]]>
</select>

OrderMapper.java加入

OrderModel getById4(int id);

測試用例

com.javacode2018.chat05.demo7.Demo7Test#getById4

@Test
public void getById4() throws IOException {
  this.before("demo7/mybatis-config1.xml");
  try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
    OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    OrderModel orderModel = mapper.getById4(2);
    log.info("{}", orderModel);
  }
}

運行結果

21:58.821 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - ==>  Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM t_order a WHERE a.id = &#63;
21:58.850 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - ==> Parameters: 2(Integer)
21:58.868 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - <==      Total: 1
21:58.868 [main] INFO  c.j.chat05.demo7.Demo7Test - null

從輸出中可以看到最后一樣輸出結果為null,sql實際上返回的是有結果的,但是結果映射的時候返回的是空。

結果解釋

由于mybatis全局配置中將autoMappingBehavior的值置為了NONE,表示全局自動映射被關閉了,而resultMapper中的orderModelMap4沒有配置autoMapping屬性,所以最終這個查詢結果不會自動映射,所以最后查詢結果為null。

PARTIAL

對除在內部定義了嵌套結果映射(也就是連接的屬性)以外的屬性進行映射,這個也是autoMappingBehavior的默認值。

mybatis-config.xml加入配置

<settings>
  <!-- 對除在內部定義了嵌套結果映射(也就是連接的屬性)以外的屬性進行映射,這個也是autoMappingBehavior的默認值。 -->
  <setting name="autoMappingBehavior" value="PARTIAL"/>
</settings>

OrderMapper.xml

<resultMap id="orderModelMap5" type="com.javacode2018.chat05.demo7.model.OrderModel">
</resultMap>

<select id="getById5" resultMap="orderModelMap5">
  <![CDATA[
  SELECT
    a.id,
    a.user_id userId,
    a.create_time createTime,
    a.up_time upTime
  FROM
    t_order a
  WHERE
    a.id = #{value}
  ]]>
</select>

OrderMapper.java加入

OrderModel getById5(int id);

測試用例

com.javacode2018.chat05.demo7.Demo7Test#getById5

@Test
public void getById5() throws IOException {
  this.before("demo7/mybatis-config2.xml");
  try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
    OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    OrderModel orderModel = mapper.getById5(2);
    log.info("{}", orderModel);
  }
}

運行結果

28:32.612 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById5 - ==>  Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM t_order a WHERE a.id = &#63;
28:32.648 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById5 - ==> Parameters: 2(Integer)
28:32.664 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById5 - <==      Total: 1
28:32.665 [main] INFO  c.j.chat05.demo7.Demo7Test - OrderModel(id=2, userId=1, createTime=1577947790, upTime=1577947790, userModel=null) 

OrderModel中的4個屬性被自動映射成功了。

結果解釋

orderModelMap5中沒有指定autoMapping屬性,所以自動映射會走全局配置的規則,即PARTIAL,會進行自動映射。

我們再來看看PARTIAL的解釋:對除在內部定義了嵌套結果映射(也就是連接的屬性)以外的屬性進行映射。這句話是什么意思?

有些復雜的查詢映射會在resultMap中嵌套一些映射(如:association,collection),當使用PARTIAL的時候,如果有嵌套映射,則這個嵌套映射不會進行自動映射了。

通過訂單id查詢出訂單以及訂單用戶的信息,sqlmap如下:

<resultMap id="orderModelMap6" type="com.javacode2018.chat05.demo7.model.OrderModel">
  <association property="userModel">
  </association>
</resultMap>

<select id="getById6" resultMap="orderModelMap6">
  <![CDATA[
  SELECT
    a.id,
    a.user_id userId,
    a.create_time createTime,
    a.up_time upTime
    b.id as user_id,
    b.name
  FROM
    t_order a,t_user b
  WHERE
    a.user_id = b.id
    AND a.id = #{value}
  ]]>
</select>

OrderModel.java

package com.javacode2018.chat05.demo7.model;

import lombok.*;

import java.util.List;

@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class OrderModel {
  private Integer id;
  private Integer userId;
  private Long createTime;
  private Long upTime;
  private UserModel userModel;
}

內部有個userModel屬性引用用戶對象。

UserModel.java

package com.javacode2018.chat05.demo7.model;

import lombok.*;

@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class UserModel {
  private Integer id;
  private String name;
}

OrderMapper.java中加入

OrderModel getById6(int id);

測試用例

com.javacode2018.chat05.demo7.Demo7Test#getById6
@Test
public void getById6() throws IOException {
  this.before("demo7/mybatis-config2.xml");
  try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
    OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    OrderModel orderModel = mapper.getById6(2);
    log.info("{}", orderModel);
  }
}


 

運行輸出

52:49.037 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - ==>  Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime, b.id as user_id, b.name FROM t_order a,t_user b WHERE a.user_id = b.id AND a.id = &#63;
52:49.066 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - ==> Parameters: 2(Integer)
52:49.087 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - <==      Total: 1
52:49.088 [main] INFO  c.j.chat05.demo7.Demo7Test - null 

sql查詢實際上是有一條記錄的,但是最后返回的是null,說明沒有進行自動映射。

FULL

自動映射所有屬性。

這次Mapper我們不動,還是下面這樣,沒有手動指定映射規則。

<resultMap id="orderModelMap6" type="com.javacode2018.chat05.demo7.model.OrderModel">
  <association property="userModel">
  </association>
</resultMap>

<select id="getById6" resultMap="orderModelMap6">
  <![CDATA[
  SELECT
    a.id,
    a.user_id userId,
    a.create_time createTime,
    a.up_time upTime
    b.id as user_id,
    b.name
  FROM
    t_order a,t_user b
  WHERE
    a.user_id = b.id
    AND a.id = #{value}
  ]]>
</select>

修改一下autoMappingBehavior的值為FULL,看看效果。

mybatis配置

<settings>
  <!-- 自動映射所有屬性 -->
  <setting name="autoMappingBehavior" value="FULL"/>
</settings>

測試用例

com.javacode2018.chat05.demo7.Demo7Test#getById6_0

@Test
public void getById6_0() throws IOException {
  this.before("demo7/mybatis-config3.xml");
  try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
    OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    OrderModel orderModel = mapper.getById6(2);
    log.info("{}", orderModel);
  }
}

運行輸出

56:05.127 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - ==>  Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime, b.id as user_id, b.name FROM t_order a,t_user b WHERE a.user_id = b.id AND a.id = &#63;
56:05.155 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - ==> Parameters: 2(Integer)
56:05.186 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - <==      Total: 1
56:05.186 [main] INFO  c.j.chat05.demo7.Demo7Test - OrderModel(id=2, userId=1, createTime=1577947790, upTime=1577947790, userModel=UserModel(id=2, name=張學友))

輸出中可以看到OrderModel所有屬性都是有值的,userModel的2個屬性也有值,userModel.id是2,我們運行一下sql看看,用戶id是多少,如下:

mysql> SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime, b.id as user_id, b.name FROM t_order a,t_user b WHERE a.user_id = b.id AND a.id = 2;
+----+--------+------------+------------+---------+-----------+
| id | userId | createTime | upTime   | user_id | name   |
+----+--------+------------+------------+---------+-----------+
| 2 |   1 | 1577947790 | 1577947790 |    1 | 張學友  |
+----+--------+------------+------------+---------+-----------+
1 row in set (0.00 sec)

user_id實際上是1,mybatis中按照sql字段和model結果字段同名進行自動映射,所以將訂單的id賦值給userModel的id屬性了。

此時需要我們orderModelMap6的配置,手動指定一下user_id和userModel.id的映射規則,如下:

<resultMap id="orderModelMap6" type="com.javacode2018.chat05.demo7.model.OrderModel">
  <association property="userModel">
    <id column="user_id" property="id"/>
  </association>
</resultMap>

再次運行測試用例

com.javacode2018.chat05.demo7.Demo7Test#getById6_0

輸出

15:02.751 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - ==>  Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime, b.id as user_id, b.name FROM t_order a,t_user b WHERE a.user_id = b.id AND a.id = &#63;
15:02.783 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - ==> Parameters: 2(Integer)
15:02.801 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById6 - <==      Total: 1
15:02.801 [main] INFO  c.j.chat05.demo7.Demo7Test - OrderModel(id=2, userId=1, createTime=1577947790, upTime=1577947790, userModel=UserModel(id=1, name=張學友)) 

這次userModel中的id正確了。

autoMapping使用

上面我們有說過,當在resultMap中指定了autoMapping屬性之后,這個resultMap的自動映射就受autoMapping屬性的控制,和mybatis中全局映射配置(autoMappingBehavior)行為無關了。

案例1

這個核心配置主要在sqlmap中,如下:

<resultMap id="orderModelMap7" type="com.javacode2018.chat05.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
    t_order a,t_user b
  WHERE
    a.user_id = b.id
    AND a.id = #{value}
  ]]>
</select>

對應測試用例

com.javacode2018.chat05.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);
  }
}

運行輸出

24:37.544 [main] DEBUG c.j.c.d.mapper.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 t_order a,t_user b WHERE a.user_id = b.id AND a.id = &#63;
24:37.589 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById7 - ==> Parameters: 2(Integer)
24:37.610 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById7 - <==      Total: 1
24:37.610 [main] INFO  c.j.chat05.demo7.Demo7Test - OrderModel(id=2, userId=1, createTime=1577947790, upTime=1577947790, userModel=UserModel(id=1, name=張學友))

OrderModel中所有屬性都自動映射成功。

自動裝配并不是那么好玩,玩不轉可能帶來一些隱患,我們看一個案例,見下面的示例2。

示例2

根據訂單編號,查詢出訂單信息,順便查詢出訂單明細列表。這個我們使用mybatis中的一對多查詢。

OrderDetaiMapper.xml加入

<select id="getListByOrderId1" resultType="com.javacode2018.chat05.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
    t_order_detail a
  WHERE
    a.order_id = #{value}
  ]]>
</select>

這個可以根據訂單的id,查詢出訂單關聯的明細列表。

OrderMapper.xml加入

<resultMap id="orderModelMap8" type="com.javacode2018.chat05.demo7.model.OrderModel" autoMapping="true">
  <collection property="orderDetailModelList" select="com.javacode2018.chat05.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
    t_order a
  WHERE a.id = #{value}
  ]]>
</select>

測試用例

com.javacode2018.chat05.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);
  }
}

運行輸出

11:06.193 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById8 - ==>  Preparing: SELECT a.id, a.user_id userId, a.create_time createTime, a.up_time upTime FROM t_order a WHERE a.id = &#63;
11:06.229 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById8 - ==> Parameters: 1(Integer)
11:06.250 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - ====>  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 = &#63;
11:06.251 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - ====> Parameters: 1(Integer)
11:06.255 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - <====      Total: 2
11:06.256 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById8 - <==      Total: 1
11:06.256 [main] INFO  c.j.chat05.demo7.Demo7Test - OrderModel(id=null, userId=2, createTime=1577947790, upTime=1577947790, userModel=null, orderDetailModelList=[OrderDetailModel(id=1, orderId=1, goodsId=1, num=2, totalPrice=17.76), OrderDetailModel(id=2, orderId=1, goodsId=1, num=1, totalPrice=16.66)])
 

注意輸出中OrderModel的id屬性,怎么是null值?主要是下面這行配置導致的

<collection property="orderDetailModelList" select="com.javacode2018.chat05.demo7.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>

上面這個配置中有個column屬性,指定的是id,此時mybatis認為你對id字段手動指定了映射關系,就跳過了對id字段到OrderModel.id屬性的自動映射,所以導致OrderModel對象的id屬性沒有賦值,此時需要我們在orderModelMap8手動指定id的映射規則,如下:

<resultMap id="orderModelMap8" type="com.javacode2018.chat05.demo7.model.OrderModel" autoMapping="true">
  <id column="id" property="id" />
  <collection property="orderDetailModelList" select="com.javacode2018.chat05.demo7.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>
</resultMap>

以上就是使用Mybatis實現自動映射,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

新乐市| 正镶白旗| 阳泉市| 宁津县| 交口县| 基隆市| 那曲县| 保靖县| 喀什市| 舞阳县| 香港| 土默特右旗| 黎城县| 仲巴县| 怀来县| 临澧县| 融水| 庐江县| 筠连县| 搜索| 崇礼县| 托克托县| 乳山市| 禹城市| 泰安市| 合川市| 罗定市| 阜阳市| 襄汾县| 宣威市| 湘潭县| 宝清县| 夏河县| 萨嘎县| 进贤县| 缙云县| 禄劝| 许昌县| 卢龙县| 黄冈市| 邢台市|