多对一处理
第一:编写一个学生的实体类
package com.zzy.pojo;
import lombok.Data;
import org.apache.ibatis.annotations.Delete;
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
注意:在student实体类中老师的属性是一个javabean对象所以在student类中老师属于复杂属性
第二:编写一个student的dao层
package com.zzy.dao;
import com.zzy.pojo.Student;
import com.zzy.pojo.Teacher;
import java.util.List;
public interface StudentMapper {
//查询学生信息通过id
Student getStudent(int id);
//查询所有的学生
List<Student> getStudents();
//查询老师
Teacher getTeacher(int id);
List<Student> getStudents1();
}
第三:编写一个学生的dao层对应的studentMapper.xml
注意:result property=“id” column=“id”
property对应你的实体类的属性 column对应你的数据库子段
<?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="com.zzy.dao.StudentMapper">
<select id="getStudent" resultType="Student">
select * from student where id=#{id}
</select>
<!-- 1,查询所有的学生信息 2根据查询的学生信息的tid来查询老师的信息-->
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!-- 复杂的属性 必须单独处理 association :对象的处理 collection:对集合的处理-->
<association property="teacher" column="tid" javaType="Student" select="getTeacher"/>
</resultMap>
<select id="getStudents" resultMap="StudentTeacher">
select *from student
</select>
<select id="getTeacher" resultType="Teacher">
select *from teacher where id=#{id}
</select>
<!-- ##########################按照结果集查询################################### -->
<resultMap id="StudentTeacher1" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
<select id="getStudents1" resultMap="StudentTeacher1">
select s.id sid,s.name sname ,t.name tname from student s ,teacher t where s.tid=t.id;
</select>
</mapper>
注意:因为老师再student中是一个对象所以要特殊处理在resultmap中进行处理
<!-- 1,查询所有的学生信息 2根据查询的学生信息的tid来查询老师的信息-->
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!-- 复杂的属性 必须单独处理 association :对象的处理 collection:对集合的处理-->
<association property="teacher" column="tid" javaType="Student" select="getTeacher"/>
</resultMap>
注意:在注入sql语句时他的属性是resultmap=id(是resultmap的id)
<select id="getStudents" resultMap="StudentTeacher">
select *from student
</select>