mybatis 一对多
实体类 @Data public class Student { private int id; private String name; private int tid; }
实体类
@Data public class Teacher { private int id; private String name; //一个老师有多个学生 private List<Student> students; }
接口
public interface TeacherMapper {//获取指定老师下的所有学生及老师的信息 Teacher getTeacher(@Param("tid") int id); }
TeacherMapper
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.rzk.mapper.TeacherMapper"> <!--按结果嵌套查询 resultMap对应下面resultMap的id--> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid, s.name sname,t.id tid,t.name tname from teacher t ,student s where s.tid = t.id AND t.id = #{tid} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!--复杂的属性,我们需要单独处理 对象 association 集合 collection javaType="'指定属性的类型 集合中的泛型信息,我们使用ofType获取 --> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap>
测试类
@Test public void getStudentByTeacher(){ SqlSession sqlSessionFactory = MybatisUtils.getSqlSessionFactory(); TeacherMapper mapper = sqlSessionFactory.getMapper(TeacherMapper.class); Teacher teacher2 = mapper.getTeacher2(1); System.out.print是、ln(teacher2); sqlSessionFactory.close(); } <!--Teacher(id=1, name=精致的猪猪女孩, students=[Student (id=1, name=小明, tid=1), Student(id=2, name=小红, tid=1), Student(id=3, name=小张, tid=1), Student(id=4, name=小李, tid=1), Student(id=5, name=小王, tid=1)])-->
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configguration核心配置文件--> <configuration> <!--导入外部配置文件--> <properties resource="db.properties"/> <!--标准日志工厂实现--> <!-- <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>--> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <!--给实体类起别名--> <typeAliases> <package name="com.rzk.pojo" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/rzk/mapper/StudentMapper.xml"/> <mapper resource="com/rzk/mapper/TeacherMapper.xml"/> <!-- <mapper class="com.rzk.mapper.TeacherMapper"/>--> <!-- <mapper class="com.rzk.mapper.StudentMapper"/>--> </mappers> </configuration>