MyBatis(十一) 注解详解

一. 注解开发

  • 注解是用于描述代码的代码. 例如:
    @Test(用于描述方法进行 junit 测试), @Override(用于描述方法的重写), @Param(用于描述属性的名称)
  • 注解的使用风格: @xxx(属性), 使用前必须先导包
  • 使用注解一般用于简化配置文件. 但是, 注解有时候也不是很友好(有时候反而更麻烦), 例如动态 SQL.
  • 关于注解的属性
    属性的设定方式是: 属性名=属性值
  • 关于属性值的类型

基本类型和 String, 可以直接使用双引号的形式
数组类型, name={值 1, 值 2, ...}; 如果数组元素只有一个, 可以省略大括号
对象类型, name=@对象名(属性)
如果属性是该注解的默认属性, 而且该注解只配置这一个属性, 可以将属性名省略

  • 注解和配置文件可以配合使用

二. MyBatis 中常用的注解---CRUD 注解

@Select: 类似于<select>
@Insert: 类似于<insert>
@Update: 类似于<update>
@Delete: 类似于<delete>

package cn.bjsxt.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import cn.bjsxt.pojo.Student;
/**
 * 通过注解,直接胜略配置文件的书写
 * 查询所有学生
 * @author chy
 *
 */
public interface StudentMapper {
    //@Select(value={"select * from t_student"})//一条语句时,可以省略大括号
    //@Select(value="select * from t_student")//使用默认值是,可以省略value
    @Select("select * from t_student")
    List<Student> selAll();
    @Insert("insert into t_student values (#{id},#{name},#{age},#{gender},#{cid})")
    int insStu(Student student);
    //0、1代表参数插入的顺序,先传入的是id,故为0,。后传入的是age,故为1
    @Update("update t_student set age=#{1} where id=#{0}")
    int updStu(int id,int age);
    @Delete("delete from t_student where id=#{0}")
    int delStu(int id);
}

三. MyBatis 中常用的注解---其他注解

@Results: 类似于<resultMap>
@Result: 类似于<resultMap>的子标签
@One: 类似于<association>
@Many: 类似于<collection>

package cn.bjsxt.mapper;
import java.util.List;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import cn.bjsxt.pojo.Student;
/**
 * 通过注解,直接省略配置文件的书写
 * results=>resultMap
 * result=>result
 * @One=>association
 * @author chy
 *
 */
public interface StudentMapper {
    @Select("select * from t_student")
    @Results(value= {
            @Result(column="id",property="id",id=true),
            @Result(property="name",column="name"),
            @Result(column="age",property="age"),
            @Result(column="gender",property="gender"),
            @Result(column="cid",property="cid"),
            @Result(property="clazz",one=@One(select="cn.bjsxt.mapper.ClazzMapper.selById"),column="cid")
    })
    List<Student> sel();
}