mybatis常用注解有:@Select、@SelectKey、@Insert、@Update、@Delete。以及结果集三大注解:@Result、@Results、@ResultMap;除此之外还有:@One、@Many等,接下来一一介绍这些注解。
@Select注解:
@Select({"select id,username,phone from db_user where id = #{key}"})User selectUserByPrimaryKey(Long key);
查询相关的SQL写在@Select注解中,花括号里面的内容可以是字符串也可以是字符串数组。
@SelectKey:
@SelectKey(statement = "select last_insert_id()" ,keyProperty = "id",keyColumn = "id",resultType = int.class,before = false) public int insert(User user);
@Insert:
@Insert({"insert into db_user(username, password, nickname, phone, email) values (#{username}, #{password}, #{nickname}, #{phone}, #{email})"})@Options(useGeneratedKeys = true, keyProperty = "id")int insertUser(User user);
添加相关的SQL写在@Insert注解中,花括号里面的内容可以是字符串也可以是字符串数组。当添加操作需要返回自增主键时可以使用@Options注释。添加属性useGeneratedKeys = true和keyProperty = "id"即可在数据添加后获取添加数据的ID值。
@Update:
@Update({"update db_user set name = #{name} where id = #{id}"})int updateUserByPrimaryKey(User user);
修改相关的SQL写在@Update注解中,花括号里面的内容可以是字符串也可以是字符串数组。
@Delete:
@Delete({"delete from db_user where id = #{key}"})int deleteUserByPrimaryKey(Long key);
删除相关的SQL写在@Delete注解中,花括号里面的内容可以是字符串也可以是字符串数组。
结果集注解:
@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 selectAll() ;
引用结果集:@Select({"select id, name, class_id from student where id = #{id}"})@ResultMap(value="studentMap")Student selectById(integer id);
@Results和@Result注解是结合起来用的,@Result注解包含在@Results注解的value属性中。
@Results 注解
@Results 注解有两个属性,分别是id和value。其中id属性对应的是XML配置中resultMap标签的id属性,这样只要在接口中写一次就可以公用一个resultMap了。而value属性对应的是XML配置中resultMap标签下的和标签,标签用id=true属性来确定。
@Result 注解
@Result 注解常用属性id、column和property。id属性是用来确定是否是id的,布尔类型。column属性是对应数据库字段的,字符串类型。property属性是对应JavaBean对象属性的,字符串类型。
@ResultMap 注解就一个作用,使用已经定义好的@Results或XML配置里已经写好的resultMap。里面的value属性即是@Results的id属性值或XML里resultMap的id属性值。
@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="com.breivty.mappers.AddressMapper.getAddress")) }) public List getAllStudents() ;
@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="com.brevity.mappers.StudentMapper.getStudentsByClassId")) }) public Class getClass(int id);
上面这些注解分别对应着xml文件的的标签,具体更复杂的写法就可以结合xml文件中的写法了,不过,当SQL有变化时都需要重新编译代码,一般情况下不建议使用注解方式,复杂的SQL还是建议在xml文件中编写,可读性比较强,也便于维护,唯一不足的就是需要切换文件比较麻烦哈。