JAVA_EE_MyBatis注解

  • 注解:为了简化配置文件.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();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,694评论 0 4
  • 最近做项目用到springboot整合mybatis,security。将其中遇到的问题做一个总结 注:本项目全程...
    huoyl0410阅读 765评论 1 2
  • 一、概述 面试,难还是不难?取决于面试者的底蕴(气场+技能)、心态和认知及沟通技巧。面试其实可以理解为一场聊天和谈...
    编辑小猿阅读 1,940评论 1 3
  • 1、什么是Mybatis? (1)Mybatis是一个半ORM(对象关系映射)框架,它内部封装了JDBC,开发时只...
    义无反顾00阅读 238评论 0 1
  • 是风和太阳找到我 它们说 嘿,还记得吗 就几年前的事儿 当时你还没有胡子 脑袋里住着一匹马 你只要在心里挥一下皮鞭...
    杜甫的杜阅读 139评论 0 1