association
标签的部分说明
- 可参考的
DTD
规范<!ELEMENT association (constructor?,id*,result*,association*,collection*, discriminator?)> <!ATTLIST association property CDATA #REQUIRED column CDATA #IMPLIED javaType CDATA #IMPLIED jdbcType CDATA #IMPLIED select CDATA #IMPLIED resultMap CDATA #IMPLIED typeHandler CDATA #IMPLIED notNullColumn CDATA #IMPLIED columnPrefix CDATA #IMPLIED resultSet CDATA #IMPLIED foreignColumn CDATA #IMPLIED autoMapping (true|false) #IMPLIED fetchType (lazy|eager) #IMPLIED >
- 可选标签元素说明
constructor
- 有参形式构造类对象实例
- 一般用于类对象没有无参构造器的情况
- 一般很少使用
id
标记主键result
标记非主键字段association
嵌套一对一的关联映射collection
嵌套一对多的关联映射discriminant
嵌套鉴别器
- 可选属性说明
property
POJO中的属性名称column
映射表中的字段名称select
指定引用mapper文件中的select标签语句columnPrefix
定义映射表字段名称的别名前缀
association
表示的一对一关系映射
使用sql关联查询实现一对一映射
resultMap
标签<resultMap type="siye.ibatis.entity.TblUser1" id="tblUserMap"> <id property="id" column="id" /> <result property="name" column="name" /> <result property="age" column="age" /> <result property="gender" column="gender" /> <!--用 columnPrefix 定义前缀,区分字段属于哪些类 --> <association property="tblRole" javaType="siye.ibatis.entity.TblRole" columnPrefix="r_"> <id property="id" column="id" /> <result property="name" column="name" /> </association> </resultMap>
select
标签<select id="getTblUserByPK" resultMap="tblUserMap" > select u.id,u.name,u.age,u.gender,r.id r_id,r.name r_name from tbl_user u left join tbl_role r on u.role_id = r.id where u.id = #{id} </select>
java
调用TblUser1 obj = dao.getTblUserByPK(1); log.info(obj);
组合sql语句实现一对一映射
resultMap
标签<resultMap type="siye.ibatis.entity.TblUser1" id="tblUserMap1"> <id property="id" column="id" /> <result property="name" column="name" /> <result property="age" column="age" /> <result property="gender" column="gender" /> <!--用 column 给指定的 select 语句传递参数 --> <!--引用外部或内部的 select 语句,若是外部加 namespace --> <association property="tblRole" column="role_id" select="getTblRoleByPK" /> </resultMap>
select
标签<select id="getTblRoleByPK" resultType="siye.ibatis.entity.TblRole"> select id,name from tbl_role where id = #{id} </select> <select id="getTblUserByPK1" resultMap="tblUserMap1"> select id,name,age,gender,role_id from tbl_user where id = #{id} </select>
java
调用TblUser1 obj1 = dao.getTblUserByPK1(1); log.info(obj1);