一对多的关联
数据表的设计
- 在我们的生活中有许多的关联关系,我们大致可以分为三类,一对一,一对多,多对多三种,在这里我们借助Mybatis较为详细的介绍一下,一对多的关联实现
- 我们这里就以类型类和对应的实体类的一对多关系为例,使用mybatis来处理这个关联关系
- 首先是对应实体的设计MyObject数据库,现在先给它三个属性,一个是id,一个是name ,还有一个我们为了方便查看自己是属于哪一类,并且自己属于的类不能是type里面没有的,所以还有一个tid关联作为外键关联type的id属性
- 对于type数据表的设计,就是id和name就可以了
实体类结构
- Type类
这里我们数据表里面是没有对应的第三个属性段,但是我们从实际使用来说,我们想知道有哪些对象是属于我这个类型的,所以我们就需要拿到对应自己id的myObject对象
public class Type {
private Integer id;
private String name;
private List<myObject> myObject;
// 省略get和set方法
}
- MyObject类
这里第三个属性也有差异,数据表里面是id,我们这里是对象,同样的我们也是为了方便,因为我们获得某个实体类的时候,我们不希望只有一个id属性,这样我们获取不了什么有效的信息
public class myObject {
private Integer id;
private String name;
private Type type;
// 省略get和set方法
}
Mapper.xml
- MyObjectMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xzw.dao.MyObjectMapper">
<select id="findMyObjectById" resultMap="MyObjectMap">
select * from myobject where id = #{id}
</select>
<resultMap id="MyObjectMap" type="xzw.bean.myObject">
<association property="type" javaType="xzw.bean.Type" column="tid" select="xzw.dao.TypeMapper.findTypeById">
</association>
</resultMap>
<!-- 下面这个是和type关联的查询-->
<select id="findMyObjectBytId" resultType="xzw.bean.myObject">
select * from myobject where tid = #{tid}
</select>
</mapper>
注解版:
public interface MyObjectMapper {
@Select("select * from myobject where id = #{id}")
@Results({
@Result(column = "tid" ,property = "type",one = @One(select = "xzw.dao.TypeMapper.findTypeById"))
})
myObject findMyObjectById(Integer id);
//注意区分,下面这个是根据类型id查询
myObject findMyObjectBytId(Integer tid);
}
- TypeMapper.xml
在这里我们只需要对列表属性进行结果映射,其他的都和数据库表结构是对应的,myBatis会帮我们自动填充,对于查询类型的时候,怎么才能得到属于自己这个类型所有MyObject对象呢?我们通过 collection标签将type的id作为参数放在select标签下的MyObject下的根据tid属性查询的语句去执行,这样我们就能得到哪些对象是对应我这个type的。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xzw.dao.TypeMapper">
<select id="findTypeById" resultMap="MyPersonList">
select * from type where id = #{id}
</select>
<resultMap id="MyPersonList" type="xzw.bean.Type">
<!-- 一对多的关系映射-->
<collection property="myObject" ofType="xzw.bean.myObject" column="id" select="xzw.dao.MyObjectMapper.findMyObjectBytId">
</collection>
</resultMap>
</mapper>
注解版:
public interface TypeMapper {
@Select("select * from type where id = #{id}")
@Results({
@Result(column = "myObject",property = "id" ,many = @Many(select = "xzw.dao.MyObject.findMyObjectBytId"))
})
Type findTypeById(Integer id);
}