mybatis学习笔记2-复合类型查询

1. 使用association和collection标签进行复合类型查询
2. discriminator标签进行分类查询,感觉是为了实现继承类的ORMaping而存在的。

复合类型. User对象中包含一个Album列表. 注意collection标签中的column取值需要和User的sql中的列名对应,这里是user_id。取Album的sql中也用到这个列名:userid=#{user_id}
<resultMap type="User" id="userMapWithAlbum">
		<id property="id" column="user_id" />
		<result property="name" column="user_name" />
		<result property ="sex" column="user_sex" />
		<result property="age" column="user_age" />
		<collection property="albums" column="user_id" ofType="Album" select="selectAlbumForUser" />
	</resultMap>
<select id="findById" parameterType="HashMap" resultMap="usermap">
		select 
			a.id as user_id,
			a.name as user_name,
			a.sex as user_sex,
			a.age as user_age
		from T_User a where a.id=#{id}
    </select>
    
    <select id="selectAlbumForUser" resultType="Album">
    	select * from T_Album where userId=#{user_id}
    </select>


分类应用,需要定义User的两个子类:GameUser和SingUser. GameUser有wins属性,SingUser有sings属性
<resultMap type="User" id="usermap">
		<id property="id" column="user_id" />
		<result column="user_name" property="name" typeHandler="example.dao.typehandler.SimpleTypeHandler"/>
		<result property ="sex" column="user_sex" />
		<result property="age" column="user_age" />
		<discriminator javaType="byte" column="user_sex">
			<case value="1" resultType="example.model.GameUser">
				<result property="wins" column="wins" />
			</case>
			<case value="0" resultType="example.model.SingUser">
				<result property="sings" column="sings" />
			</case>
		</discriminator>
	</resultMap>

你可能感兴趣的:(mybatis)