MyBatis注解详解

时间:2022-07-22
本文章向大家介绍MyBatis注解详解,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  1. 注解开发

a) 注解是用于描述代码的代码. 例如: @Test(用于描述方法 进行 junit 测试), @Override(用于描述方法的重写), @Param(用于描述属性的名称) b) 注解的使用风格: @xxx(属性), 使用前必须先导包 c) 使用注解一般用于简化配置文件. 但是, 注解有时候也不 是很友好(有时候反而更麻烦), 例如动态 SQL. d) 关于注解的属性  属性的设定方式是: 属性名=属性值 e) 关于属性值的类型  基本类型和 String, 可以直接使用双引号的形式  数组类型, name={值 1, 值 2, …}; 如果数组元素只有 一个, 可以省略大括号  对象类型, name=@对象名(属性)  如果属性是该注解的默认属性, 而且该注解只配置这 一个属性, 可以将属性名省略 f) 注解和配置文件可以配合使用

2 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);
}

3 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();
	
	
	
}