常用注解分为三大类:SQL语句映射,结果集映射和关系映射。
1、SQL语句映射
@Insert:
实现新增功能
@Insert("insert into user(id,name) values(#{id},#{name})") @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id") public int insert(User user);
@Select注解:
实现查询功能
@Select("Select * from user") @Results({ @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name"), @Result(column = "sex", property = "sex"), @Result(column = "age", property = "age") }) List<User> queryAllUser();
@SelectKey注解:
插入后,获取id的值
以mysql为例,mysql在插入一条数据后,如何能获得到这个自增id的值呢?使用select last_insert_id() 可以取到最后生成的主键。
@Insert("insert into user(id,name) values(#{id},#{name})") @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id") @SelectKey(statement = "select last_insert_id()" ,keyProperty = "id",keyColumn = "id",resultType = int.class,before = false) public int insert(User user);
备注:before属性,默认是true,在执行插入语句之前,执行select last_insert_id()。如果设置为flase,则在插入这个语句之后,执行select last_insert_id()
@Insert注解:
实现插入功能
@Insert("insert into user(name,sex,age) values(#{name},#{sex},#{age}") int saveUser(User user);
@Update注解:
实现更新功能
@Update("update user set name= #{name},sex = #{sex},age =#{age} where id = #{id}") void updateUserById(User user);
@Delete注解:
实现删除功能
@Delete("delete from user where id =#{id}") void deleteById(Integer id);
2、结果集映射
@Result,@Results,@ResultMap是结果集映射的三大注解。
首先说明一下@Results各个属性的含义,id为当前结果集声明唯一标识,value值为结果集映射关系,@Result代表一个字段的映射关系,column指定数据库字段的名称,property指定实体类属性的名称,jdbcType数据库字段类型,@Result里的id值为true表明主键,默认false;使用@ResultMap来引用映射结果集,其中value可省略。
声明结果集映射关系代码:
@Select({"select id, name, class_id from student"}) @Results(id="studentMap", value={ @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();
引用结果集代码:
@Select({"select id, name, class_id from student where id = #{id}"}) @ResultMap(value="studentMap") Student selectById(integer id);
这样就不用每次需要声明结果集映射的时候都复制冗余代码,简化开发,提高了代码的复用性。
3、关系映射
3.1、@one注解:用于一对一关系映射
@Select("select * from student") @Results({ @Result(id=true,property="id",column="id"), @Result(property="name",column="name"), @Result(property="age",column="age"), @Result(property="address",column="address_id",one=@One(select="cn.mybatis.mydemo.mappers.AddressMapper.getAddress")) }) public List<Student> getAllStudents();
3.2、@many注解:用于一对多关系映射
@Select("select * from t_class where id=#{id}") @Results({ @Result(id=true,column="id",property="id"), @Result(column="class_name",property="className"), @Result(property="students", column="id", many=@Many(select="cn.mybatis.mydemo.mappers.StudentMapper.getStudentsByClassId")) }) public Class getClass(int id);
REF
http://www.mybatis.cn/archives/739.html
https://www.jianshu.com/p/34fa03d9bc8d
https://blog.csdn.net/u013452337/article/details/100693418
https://blog.csdn.net/u012621115/article/details/50970195