在没有映射文件的情况下,如何实现查询呢。
在上次的代码上(MyBatis实现多表查询方式二)删掉3个映射文件,然后修改配置文件中加载映射文件为加载Dao接口:
<mappers>
<mapper class="com.xyj.dao.GenderDao"/>
<mapper class="com.xyj.dao.GradeDao"/>
<mapper class="com.xyj.dao.StudentDao"/>
</mappers>
但是sql语句和映射关系写在哪呢?自然是Dao层。
修改GenderDao如下:
@Select("select * from gender where gid=#{gid}")
Gender findById(@Param("gid")int gid);
GradeDao:
@Select("select * from grade where gid=#{gid}")
Grade findById(@Param("gid")int gid);
StudentDao修改如下:
@Select("select * from student")
@Results(id="stures",value= {
@Result(id=true,column="stuid",property="stuid"),
@Result(column="stuname",property="stuname"),
@Result(column="stupwd",property="stupwd"),
@Result(column="stuage",property="stuage"),
@Result(property="gender",column="ggid",one=@One(select="com.xyj.dao.GenderDao.findById")),
@Result(property="grade",column="gid",one=@One(select="com.xyj.dao.GradeDao.findById"))
})
List<Student> findThreeTables();
/**
* 这个方法仅仅是为了说明Results可以复用!!!
*/
@Select("select * from student")
@ResultMap("stures")
List<Student> findAll();
修改完成了,现在就可以在没有映射文件的情况下进行连表查询
@org.junit.Test
public void testThreeTables() {
SqlSession session = MyBatisUtils.getSqlSession();
StudentDao sd = session.getMapper(StudentDao.class);
List<Student> list = sd.findThreeTables();
list.forEach(System.out::println);
}