处理属性和字段不一致
通过resultMap
当Java中实体类属性和数据库字段不一致的时候,我们可以通过resultMap进行映射,例如我们要查询一个user表中的用户的全部信息,在Java中属性是password,而数据库字段是pwd,所以我们的就引入了resultMap来取代resultType
<resultMap id="UserMap" type="com.com.hzy.pojo.User">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="pwd"/>
</resultMap>
<select id="getUserList" resultMap="UserMap">
select * from user
</select>
通过SQL语句别名
在查询指定字段的时候,把不一致的字段指定别名为Java属性
<select id="getUserByNameAndPassword" resultType="com.hzy.pojo.User">
select id,username,pwd password from user where username = #{username} and pwd = #{password}
</select>
处理复杂属性
当出现联表查询的时候,会出现一对一或一对多的关系
如果有两张表,分别是学生和老师
站在学生的角度看,一个学生是对应一个老师的,这是一对一,在学生信息表中只有老师的id而没有老师的名字,我们想要通过联表查询查询出学生的信息和老师的名字。
此时的Student类是带有复杂类型Teacher的类
那么我们在进行resultMap映射的时候,会牵扯到对象的映射,用到association标签
<resultMap id="studentTeacher" type="com.hzy.pojo.Student">
<result property="id" column="id"/>
<result property="studentName" column="student_name"/>
<association property="teacher" javaType="com.hzy.pojo.Teacher">
<result property="teacherName" column="teacher_name"/>
</association>
</resultMap>
<select id="findAllStudent" resultMap="studentTeacher">
SELECT s.id,s.student_name,t.teacher_name FROM student s,teacher t
</select>
如果我们站在老师的角度来看,那就是一个老师对应多个学生,这是一对多
此时用到一个标签是collection
<resultMap id="teacherStudent" type="com.hzy.pojo.Teacher">
<result property="id" column="id"/>
<result property="teacherName" column="teacher_name"/>
<collection property="studentList" ofType="com.hzy.pojo.Student">
<result property="id" column="id"/>
<result property="studentName" column="student_name"/>
<result property="teacherId" column="teacher_id"/>
</collection>
</resultMap>
<select id="findAllTeacher" resultMap="teacherStudent">
SELECT t.id,t.teacher_name,s.student_name FROM teacher t,student s
</select>