0
点赞
收藏
分享

微信扫一扫

JAVA_EE_MyBatis注解

静鸡鸡的JC 2021-09-28 阅读 95
  • 注解:为了简化配置文件.Mybatis 的注解简化 mapper.xml 文件.
  • 范围:如果涉及动态 SQL 依然使用 mapper.xml
  • mapper.xml 和注解可以共存.
使用注解时 mybatis.xml 中<mappers>使用
  1. <package/>
  2. <mapper class=””/>

  1. 实现查询
@Select("select * from teacher")
List<Teacher> selAll();
  1. 新增
@Insert("insert into teachervalues(default,#{name})")
int insTeacher(Teacher teacher);
  1. 修改
@Update("update teacher set name=#{name} where id=#{id}")
int updTeacher(Teacher teacher);
  1. 删除
@Delete("delete from teacher where id=#{0}")
int delById(int id);

  1. 使用注解实现<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();
-----------------------------------------------
实现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();
举报

相关推荐

0 条评论