- 注解:為了簡化配置文件.Mybatis 的注解簡化 mapper.xml 文件.
- 范圍:如果涉及動態(tài) SQL 依然使用 mapper.xml
- mapper.xml 和注解可以共存.
使用注解時 mybatis.xml 中<mappers>使用
- <package/>
- <mapper class=””/>
- 實現(xiàn)查詢
@Select("select * from teacher")
List<Teacher> selAll();
- 新增
@Insert("insert into teachervalues(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);
- 使用注解實現(xiàn)<resultMap>功能
- N+1 舉例啊犬,但對象和多對象
在 StudentMapper 接口添加查詢
@Select("select * from student where tid=#{0}")
List<Student> selByTid(int tid);
- 在 TeacherMapper 接口添加
@Results() 相當于<resultMap>
@Result() 相當于<id/>或<result/>
@Result(id=true) 相當與<id/>
@Many() 相當于<collection/>
@One() 相當于<association/>
@Results(value={
@Result(id=true,property="id",column="id"),
@Result(property="name",column="name"),
@Result(property="list",column="id",many=@Many(select="com.bjsxt.mapper.StudentMapper.selByTid"))
})
@Select("select * from teacher")
List<Teacher> selTeacher();
-----------------------------------------------
實現(xiàn)association
@Results(value= {
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="pid",property="pid"),
@Result(property="people",column="pid",one=@One(select="com.qdl.mapper.PeopleMapper.selById"))
})
@Select("select * from child")
List<Child> selAll2();