mybatis association 问题
诸位请看一下这个场景,实体对象
public class QueryTestEntity { String name; Object obj; String userId; public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
mybatis配置
<resultMap type="QueryTestEntity" id="QueryTestEntityMap1"> <result column="NAME" property="name" /> </resultMap> <resultMap type="QueryTestEntity" id="QueryTestEntityMap"> <result column="NAME" property="name" /> <association property="obj" resultMap="QueryTestEntityMap1" /> //这个关联对象就是为了做一个例子,其他对象也会有这个现象 </resultMap>
查询配置如下:
<select id="TestMap1" resultType="QueryTestEntity" parameterType="java.util.HashMap"> SELECT * FROM (SELECT PHONE_NUMBER NAME,USER_ID FROM test_table ORDER BY PHONE_NUMBER DESC ) </select> <select id="TestMap2" resultMap="QueryTestEntityMap" parameterType="java.util.HashMap"> SELECT * FROM (SELECT PHONE_NUMBER NAME,USER_ID FROM test_table ORDER BY PHONE_NUMBER DESC) </select>
执行结果为:
2016-06-20 18:30:25 [ main:3436 ] - [ DEBUG ] ==> Preparing: SELECT * FROM (SELECT PHONE_NUMBER NAME,USER_ID FROM test_table ORDER BY PHONE_NUMBER DESC ) 2016-06-20 18:30:25 [ main:3437 ] - [ DEBUG ] ==> Parameters: 2016-06-20 18:30:25 [ main:3619 ] - [ DEBUG ] <== Total: 40 result2:40 2016-06-20 18:30:25 [ main:3619 ] - [ DEBUG ] ==> Preparing: SELECT * FROM (SELECT PHONE_NUMBER NAME,USER_ID FROM test_table ORDER BY PHONE_NUMBER DESC) 2016-06-20 18:30:25 [ main:3619 ] - [ DEBUG ] ==> Parameters: 2016-06-20 18:30:26 [ main:3803 ] - [ DEBUG ] <== Total: 40 result3:3
数据说明:其中test_table表中的手机号为重复手机号(其中有三个是不同的),最主要想说的是查询结果和映射的结果是不一致的。但是如果把映射修改为如下:
<resultMap type="QueryTestEntity" id="QueryTestEntityMap"> <result column="NAME" property="name" /> <result column="USER_ID" property="userId" />//新增USERID属性,这个属性唯一 <association property="obj" resultMap="QueryTestEntityMap1" /> //这个关联对象就是为了做一个例子,其他对象也会有这个现象 </resultMap>
执行结果如下:
2016-06-20 18:50:26 [ main:3509 ] - [ DEBUG ] ==> Preparing: SELECT * FROM (SELECT PHONE_NUMBER NAME,USER_ID FROM test_table ORDER BY PHONE_NUMBER DESC) 2016-06-20 18:50:26 [ main:3510 ] - [ DEBUG ] ==> Parameters: 2016-06-20 18:50:27 [ main:3750 ] - [ DEBUG ] <== Total: 40 result3:40
实验结论证明:
1、通过association对象映射对象,如果值相同会有一些问题,映射结果和查询结果不一致(仅出现在resultMap这个对象上),个人认为这是一个bug,解决方案为映射结果上添加唯一属性,即可。
2、没使用association 功能的对象不会出现这个现象。
CREATE TABLE test_table ( phone_number VARCHAR2(100), USER_ID VARCHAR2(100) )
mybatis版本:mybatis-3.2.8