<?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要和映射器接口的全路径名相同(如果你打算使用接口的话) -->
<mapper namespace="com.lrl.dao.ScoreDao">
<!-- Score映射结果集 -->
<resultMap type="ScoreEntity" id="scoreResult">
<id property="sid" column="sid" />
<result property="scoreName" column="scoreName" />
<!--类型关联-->
<association property="student" column="uid" javaType="StudentEntity"
resultMap="studentResult" >//使用resultMap="studentResult"把两表属性联合在一起
<id property="uid" column="uid"/>
<result property="studentName" column="studentName"/>
</association>
//association也可以这样写:
<association property="student" column="uid" javaType="StudentEntity">//在里面添加属性,和使用resultMap="studentResult"性质一样
<id property="uid" column="uid"/>
<result property="studentName" column="studentName"/>
</association>
//association还可以这样写:
<association property="student" column="uid" javaType="StudentEntity"
select="findStudentById" >//会照成N+1问题,不大好
</association>
</resultMap>
<!-- Student映射结果集 -->
<resultMap type="StudentEntity" id="studentResult">
<id property="uid" column="uid" />
<result property="studentName" column="studentName" />
<collection property="score" ofType="ScoreEntity" >
<id property="sid" column="sid" />
<result property="scoreName" column="scoreName" />
</collection>
</resultMap>
//PS:resultMap里还有<constructor></constructor><discriminator></discriminator>等标签,详情请参照文档,这里只是简介而已!
<!-- 定义映射语句 ,id等价于方法名-->//resultType是返回类型,resultMap是映射结果集
<select id="findById" parameterType="Integer" resultType="ScoreEntity">
select
* from Score s where s.sid=#{sid}//#{}会自动匹配参数,暂且这里面的命名随意,但是并不是所有的都随意的。所以建议还是根据实体类里的命名把
</select>
<select id="findScoreToStudent" parameterType="Integer"
resultMap="scoreResult">
select * from Score s left outer join Student u on
s.uid=u.uid where s.sid=#{sid}//使用resultMap,可以进行表之间的级联关系,如果用resultType使用级联,则会空指针.
</select>
<select id="findStudentToScore" parameterType="Integer"
resultMap="studentResult">
select * from Student u left outer join Score s on
u.uid=s.uid where u.uid=#{uid}
</select>
<update id="updateByEntity" parameterType="ScoreEntity">
update Score s set s.scoreName=#{scoreName} where s.sid=#{sid}<!--
这里#{}里的是ScoreEntity的属性,不能随意命名!
-->
</update>
//还有<insert></insert>,<delete></delete>标签等。希望自己动手尝试使用这些标签。
</mapper>
(4)映射器接口:
public interface ScoreDao {
public Score findById(Integer sid);
public Score findScoreToStudent(Integer sid);
public void updateByEntity(Score score);
public Student findStudentToScore(Integer uid);
}
//如果觉得在UserMapper.xml(映射器)配置<select></select><update></update>等映射语句麻烦。那么可以在接口的定义方法上面使用注解@Select、@Insert等如:
@Select("select * from Score s where s.sid=#{sid}")
public Score findById(Integer sid);