resultMap实现关联单个对象(n+1方式查询)
测试
package com.ning.test;
import com.ning.pojo.Student;
import com.ning.pojo.Teacher;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
//使用resultMap实现单表映射
//使用resultMap实现关联单个对象(n+1方式) n+1查询方式 先查询出某个表的全部信息
//根据这个表的信息查询另一个表的信息
//与业务装配的区别 在service里面写的代码,由mybatis完成装配
//在student实现类包含了一个teacher对象 在TeacherMapper中进行查询
//在StudentMapper中进行调用 property属性:对象在类中的属性名 association装配一个对象时使用
//column把当前表的哪个列的值传递给另一个查询作为参数
//大前提使用的是n+1方式时,如果列名和属性名相同时可以不配置,使用Auto Mapping特性
//但是mybatis只会给作为参数传递的列装配一次,所以需要自己在配一次
public class Test {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
List<Student> list = session.selectList("com.ning.mapper.StudentMapper.selAll");
System.out.println(list);
}
}
mapper
package com.ning.mapper;
import com.ning.pojo.Student;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface StudentMapper {
@Select("select s.id,s.name,age,tid,t.id `teacher.id`,t.name `teacher.name` from student s left join teacher t on s.tid=t.id")
List<Student> selAll();
@Select("select * from student where tid=#{0}")
List<Student> selByTid(int tid);
}
package com.ning.mapper;
import com.ning.pojo.Teacher;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface TeacherMapper {
@Select("select * from teacher")
List<Teacher> selAll();
@Insert("insert into teacher values(default,#{name})")
int insTeacher(Teacher teacher);
@Update("update teacher set name=#{name} where id=#{id}")
int updTeacher(Teacher teacher);
@Delete("delete from teacher where id=#{0}")
int delById(int id);
@Results(value = {
@Result(id =true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "list",column = "id",many = @Many(select = "com.ning.mapper.StudentMapper.selByTid"))
})
@Select("select * from teacher")
List<Teacher> selTeacher();
List<Teacher> selAll2();
}
<?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.ning.mapper.TeacherMapper">
<select id="selAll2" resultType="teacher">
select * from teacher
</select>
</mapper>