3.3.14 注解
十四、注解
1. 注解开发
(1) 注解是用于描述代码的代码.
例如:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。@Test(用于描述方法进行 junit 测试 ),
@Override(用于描述方法的重写 ),
@Param(用于描述属性的名称)
(2) 注解的使用风格: @xxx(属性), 使用前必须先导包
(3) 使用注解一般用于简化配置文件. 但是, 注解有时候也不
是很友好(有时候反而更麻烦), 例如动态 SQL.
(4) 关于注解的属性
属性的设定方式是: 属性名 =属性值
(5)关于属性值的类型
基本类型和 String, 可以直接使用双引号的形式
数组类型, name={值 1, 值 2, ...}; 如果数组元素只有一个, 可以省略大括号
对象类型, name=@对象名 (属性)
如果属性是该注解的默认属性, 而且该注解只配置这一个属性, 可以将属性名省略
(6) 注解和配置文件可以配合使用
2. MyBatis 中常用的注解
(1) CRUD 注解
@Select: 类似于<select>
@Insert: 类似于<insert>
@Update: 类似于<update>
@Delete: 类似于<delete>
package com.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 com.bjsxt.pojo.Student;
public interface StudentMapper {
@Select("select * from t_student")
List<Student> selAll();
@Insert("insert into t_student values (default, #{name}, #{age},#{gender}, #{cid})")
int insStu(Student student);
@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);
}
(2) 其他注解
@Results: 类似于<resultMap>
@Result: 类似于<resultMap>的子标签
@One: 类似于<association>
@Many: 类似于<collection>
public interface StudentMapper {
@Select("select * from t_student")
@Results(value = {
@Result(column="id", property="id", id=true),
@Result(column="name", property="name"),
@Result(column="age", property="age"),
@Result(column="gender", property="gender"),
@Result(column="cid", property="cid"),
@Result(property="clazz",
one=@One(select="com.bjsxt.mapper.ClazzMapper.selById"),
column="cid")
})
List<Student> sel();
}
public interface ClazzMapper {
@Select("select * from t_class where id=#{0}")
Clazz selById(int id);
}
