对象属性存在对象或者list对象mybatis如何配置映射

2022-08-27 10:17:17

YuanGong.java 对象有以下属性

	private int id;
	private String name;
	private String sal;
	private String sex;
	private Person person;
	private List<Person> pList;

Person.java对象

	private int id;
	private String name;
	private int age;
	private String sex;
	private Date date;

这里假设person的id,name跟YuanGong的id和name有关联,也就是说用yuangong表里面的id或者name能从perosn表里查到记录,且有一对多(所以会存在list属性)。

mybatis 配置 yuangong

<resultMap type="entiry.YuanGong" id="YGmapper">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sal" column="sal"/>
<result property="sex" column="sex"/>
<result property="sex" column="sex"/>
<association property="person" column="{tid=id,tname=name}" select="selectPerson"/>
 <collection property="pList" ofType="entiry.Person"
  select="selectPersonList" column="name" javaType="ArrayList"/>
</resultMap>

person 配置

<resultMap type="entiry.Person" id="personM">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="date" column="date" jdbcType="DATE"/>
</resultMap>

两个select

<select id="selectPerson" parameterType="java.util.Map" resultMap="personM">
select * from PERSON where id=#{tid} and name=#{tname}
</select>

<select id="selectPersonList" parameterType="java.lang.String" resultMap="personM">
select * from PERSON where name=#{name}
</select>

查询例子

<select id="selectEmp" parameterType="entiry.YuanGong" resultMap="YGmapper">
select * from yuangong
</select>

其实这里配置映射主要就是association 跟collection 标签里面这个select=“selectPerson"属性
column=”{tid=id,tname=name}"表示
map.put(“tid”,yuangong.id);
map.put(“tname”,yuangong.name);
然后执行

<select id="selectPerson" parameterType="java.util.Map" resultMap="personM">
select * from PERSON where id=#{tid} and name=#{tname}
</select>

传入的map里面就有对应的tid值跟tname值了。

执行selectEmp,
可以看到日志分别执行了三段sql
select * from yuangong;
select * from PERSON where name=#{name};
select * from PERSON where id=#{tid} and name=#{tname};
debugger模式下可以看到yuangong对象属性都有值了

  • 作者:五年达尔文
  • 原文链接:https://blog.csdn.net/weixin_40648117/article/details/83060307
    更新时间:2022-08-27 10:17:17