前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >MyBatis注解详解

MyBatis注解详解

作者头像
时间静止不是简史
发布2020-07-24 17:21:28
发布2020-07-24 17:21:28
56900
代码可运行
举报
文章被收录于专栏:Java探索之路Java探索之路
运行总次数:0
代码可运行
  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>

代码语言:javascript
代码运行次数:0
复制
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>

代码语言:javascript
代码运行次数:0
复制
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();
	
	
	
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/03/14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档