MyBatis中使用@Results注解來映射查詢結果集到實體類屬性。
(1)@Results的基本用法。當數據庫字段名與實體類對應的屬性名不一致時,可以使用@Results映射來將其對應起來。column為數據庫字段名,porperty為實體類屬性名,jdbcType為數據庫字段數據類型,id為是否為主鍵。
@Select({"select id, name, class_id from my_student"})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
@Result(column="class_id", property="classId", jdbcType=JdbcType.INTEGER)
})
List<Student> selectAll();
如上所示的數據庫字段名class_id與實體類屬性名classId,就通過這種方式建立了映射關系。名字相同的可以省略。
(2)@ResultMap的用法。當這段@Results代碼需要在多個方法用到時,為了提高代碼復用性,我們可以為這個@Results注解設置id,然后使用@ResultMap注解來復用這段代碼。
@Select({"select id, name, class_id from my_student"})
@Results(id="studentMap", value={
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="class_id", property="classId", jdbcType=JdbcType.INTEGER)
})
List<Student> selectAll();
@Select({"select id, name, class_id from my_student where id = #{id}"})
@ResultMap(value="studentMap")
Student selectById(integer id);
(3)@One的用法。當我們需要通過查詢到的一個字段值作為參數,去執行另外一個方法來查詢關聯的內容,而且兩者是一對一關系時,可以使用@One注解來便捷的實現。比如當我們需要查詢學生信息以及其所屬班級信息時,需要以查詢到的class_id為參數,來執行ClassesMapper中的selectById方法,從而獲得學生所屬的班級信息。可以使用如下代碼。
@Select({"select id, name, class_id from my_student"})
@Results(id="studentMap", value={
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="class_id", property="myClass", javaType=MyClass.class,
one=@One(select="com.example.demo.mapper.MyClassMapper.selectById"))
})
List<Student> selectAllAndClassMsg();
(4)@Many的用法。與@One類似,只不過如果使用@One查詢到的結果是多行,會拋出TooManyResultException異常,這種時候應該使用的是@Many注解,實現一對多的查詢。比如在需要查詢學生信息和每次考試的成績信息時。
@Select({"select id, name, class_id from my_student"})
@Results(id="studentMap", value={
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="class_id", property="classId", jdbcType=JdbcType.INTEGER),
@Result(column="id", property="gradeList", javaType=List.class,
many=@Many(select="com.example.demo.mapper.GradeMapper.selectByStudentId"))
})
List<Student> selectAllAndGrade();
(5)傳遞多個參數。首先我們給這張表增加age(年齡)和gender(性別)兩個參數。當我們需要根據age和gender查詢學生的午餐,這時需要改寫column屬性的格式。等號左側的age和gender對應java接口的參數,右側的對應數據庫字段名。即將查到的my_student表中age和gender字段的值,分別賦給getLunchByAgeAndGender方法中的age和gender參數,去查詢對應的name(午餐名)。
@Select("select id, name, age, gender from my_student")
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="class_id", property="classId", jdbcType=JdbcType.INTEGER),
@Result(column="{age=age,gender=gender}", property="lunch",
one=@One(select="com.example.demo.mapper.StudentMapper.getLunchByAgeAndGender")),
})
List<Student> selectAllAndLunch();
@Select("select name from lunch where student_age = #{age} and student_gender = #{gender}")
String getLunchByAgeAndGender(@Param("age") int age, @Param("gender") int gender);
