-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Description
MyBatis version
3.2.7
Database vendor and version
Postgresql 9.6.6, Oracle 12
There is a strange behavior with association ID if this ID in master table is null: MyBatis will set this association ID as ID of master table.
Test case or example project
Shema and data:
CREATE TABLE public.master (
id SERIAL,
slave_id INTEGER,
CONSTRAINT master_pkey PRIMARY KEY(id)
);
INSERT INTO public.master (id, slave_id) VALUES (1, 2);
INSERT INTO public.master (id, slave_id) VALUES (2, 1);
INSERT INTO public.master (id, slave_id) VALUES (3, NULL);
CREATE TABLE public.slave (
id SERIAL,
name VARCHAR(100),
CONSTRAINT slave_pkey PRIMARY KEY(id)
)
INSERT INTO public.slave (id, name) VALUES (1, 'first');
INSERT INTO public.slave (id, name) VALUES (2, 'second');
mapper.xml:
<select id="selectMasters" resultMap="masterResultMap">
select m.*, s.id as slaveid, s.name as name
from public.master m
left join public.slave s on s.id = m.slave_id
order by m.id ASC
</select>
<resultMap id="slaveResult" type="learnspring.springmybatis.Slave" autoMapping="true">
<result property="id" column="slaveid" />
<result property="name" column="name" />
</resultMap>
<resultMap id="masterResultMap" type="learnspring.springmybatis.Master">
<result property="id" column="id" />
<result property="slave_id" column="slave_id" />
<association property="slave" column="slave_id" resultMap="slaveResult"/>
</resultMap>
java:
List<Master> masters = session.selectList("learnspring.springmybatis.BlogMapper.selectMasters");
for (Master m : masters) {
System.out.println(
"master.id:" + m.getId()
+ " master.slave_id:" + m.getSlave_id()
+ " master.slave.id:" + (null != m.getSlave() ? m.getSlave().getId() : null)
+ " master.slave.name:" + (null != m.getSlave() ? m.getSlave().getName() : null)
);
}
Expected result
master.id:1 master.slave_id:2 master.slave.id:2 master.slave.name:second
master.id:2 master.slave_id:1 master.slave.id:1 master.slave.name:first
master.id:3 master.slave_id:null master.slave.id:null master.slave.name:null
Actual result
master.id:1 master.slave_id:2 master.slave.id:2 master.slave.name:second
master.id:2 master.slave_id:1 master.slave.id:1 master.slave.name:first
master.id:3 master.slave_id:null master.slave.id:3 master.slave.name:null
It can be cured by adding to association property 'notNullColumn':
<resultMap id="masterResultMap" type="learnspring.springmybatis.Master">
<result property="id" column="id" />
<result property="slave_id" column="slave_id" />
<association property="slave" column="slave_id" resultMap="slaveResult" notNullColumn="slave_id"/>
</resultMap>
If do like that, MyBatis parses association correctly.
I do not know, there is a feature or bug, but I was very confused when saw such behavior in my work project.
Thanks a lot for yours work.
Metadata
Metadata
Assignees
Labels
No labels