MyBatis实现注解开发
一、准备工作
准备工作参考上期博客准备工作
https://editor.csdn.net/md/?articleId=115219264
二、注解开发
2.1 概念
与servlet一样在最开始时为了框架的灵活性,使用的xml配置文件的方式进行框架的搭建,但是xml文件的书写任然很繁琐,为了简化开发针对于繁琐的配置推出了相对应的注解进行功能的替换,简化一些简单的配置操作,但是对于mybatis的核心配置文件建议不要使用注解进行配置,一般使用注解的都是mapper的配置文件,但是会降低灵活性,所以目前的开发都是将注解与配置组合使用
2.2 常用注解
2.2.1 @Param()参数注解
在mapper接口与xml配置时,接口中的方法名与对应的id匹配,但是参数一般使用一个参数,并且mybatis拥有类型解析器,会自动获取对应的参数数据(mapper接口参数列表的变量与xml中实际获取的变量名没有关联),是由对应的解析器进行解析获取,如果获取不到,也会在错误信息中提示可以使用的参数名列表,如果想传递多个不同类型的参数并指定传递的变量名,那么就必须使用@Param()参数注解
Parameter 'arr[参数]' not found. Available parameters are [array]
在使用@Param注解前如果没有找到会提示
Parameter 'aid' not found. Available parameters are [arg0, arg1, param1, param2]
在使用@Param注解在对应的接口中设置绑定的变量名时会将指定名加入参数列表
//根据id修改名字
//@Param参数绑定 为指定的参数 绑定一个名字 可以在对应的mapper.xml中直接使用名字获取对应的值
int updateAnameByAid(@Param("aid") int aid,@Param("aname") String aname);
Parameter 'id' not found. Available parameters are [aname, aid, param1, param2]
2.2.2 @Select()查询注解
语法:@Select(value=“查询语句”)可以简写为@Select(“查询语句”)
等价于mapper.xml中的
如果没有设置参数与返回值类型,默认使用当前的方法参数与返回值作为使用
//查询所有数据
@Select("select * from author")
ArrayList<Author> selectAll();
等价于
<select id="selectAll" resultType="com.yunhe.vo.Author">
select *
from author
</select>
//根据id查询
@Select("select * from author where aid= #{aid}")
Author selectByAid(@Param("aid") int aid);
2.2.3 @Insert()添加注解
语法:@Insert(value=“添加语句”)可以简写为@Insert(“添加语句”)
等价于mapper.xml中的
注意:在进行赋值时#{属性}是参数的属性 需要提供getter方法才能获取
如果没有设置参数,默认使用当前的方法参数作为使用
//添加
@Insert("insert into author (aname,aage,atel,aaddress)values(#{aname},#{aage},#{atel},#{aaddress})")
int insert(Author author);
2.2.4 @Update()修改注解
语法:@Update(value=“修改语句”)可以简写为@Update(“修改语句”)
等价于mapper.xml中的
如果没有设置参数,默认使用当前的方法参数作为使用
// 通过aid修改aname
@Update("update author set aname = #{name} where aid = #{id} ")
int updateAnameByAid(@Param("id") int id, @Param("name") String name);
2.2.5 @Delete()删除注解
语法:@Delete(value=“删除语句”)可以简写为@Select(“删除语句”)
等价于mapper.xml中的
如果没有设置参数,默认使用当前的方法参数作为使用
//根据id删除
@Delete("delete from author where aid=#{aid}")
int delete(@Param("aid") int id);