Mybatis注解
Mybatis注解是用来替换Mybatis映射文件的,使用注解可以减少文件开发的数量。
Mybatis常用注解如下:
@Insert:实现新增
@Select:实现查询
@Update:实现更新
@Delete:实现删除
@Result:实现结果集的封装
@Results:可以与Result一起使用,实现多个结果集的封装
@ResultMap:实现引用@Results定义的封装
@One:实现一对一结果集的封装
@Many:实现一对多结果集的封装
@SelectProvider:实现动态SQL映射
@CacheNamespace:实现注解二级缓存的使用
Mybatis配置文件设置
在使用Mybatis注解的时候需要首先配置Mybatis配置文件中的mappers。
<mappers>
<package name="org.lanqiao.dao"/>
</mappers>
常用注解CRUD操作:
//不需要返回主键 public interface StudentMapper{ @Insert("insert into student (stud_id, name, email, addr_id, phone)values(#{studId},#{name},#{email},#{address.addrId},#{phone})") int insertStudent(Student student); } //MySQL数据库返回主键 public interface StudentMapper{ @Insert("insert into student (name,email,addr_id,phone)values(#{name},#{email},#{address.addrId},#{phone})") @Options(useGeneratedKeys=true,keyProperty="studId") int insertStudent(Student student); } //Oracle数据库返回主键 public interface StudentMapper{ @Insert("insert into student (name,email,addr_id,phone)values(#{name},#{email},#{address.addrId},#{phone})") @SelectKey(statement="select stud_id_seq.nextval from dual",keyProperty="studId",resultType=int.calss,before=true) int insertStudent(Student student); } //更新操作 @Update("update students set name=#{name},email=#{email}") int updateStudent(Student student); //删除操作 @Delete("delete form students where stud_id=#{studId}") int deleteStudent(int studId) //查询操作 @Select("select name,email,phone from students where stud_id=#{studId}") Student findStudentById(Integer studId);
结果集注解:
@Select("select name,email,phone from students where stud_id=#{studId}") @Results({ @Result(id=true,column="stud_id",property="studId"), @Result(column="name",property="name"), @Result(column="email",property="email"), @Result(column="phone",property="phone") }) Student findStudentById(Integer studId); 结果注解有一个缺点,就是在一个查询方法前面都要写一遍,不能重用。解决这个问题方案是: 定义一份结果映射文件如下所示: <mapper namespace="com.mybatis3.mappers.StudentMapper"> <resultMap type="Student" id="StudentResult"> ....... </resultMap> @Select("select name,email,phone from students where stud_id=#{studId}") @ResultMap("com.mybatis3.mappers.StudentMapper.StudentResult") Student findStudentById(Integer studId);
动态SQL注解:
方式一:
@Select("<script>select * from user <if test=\"id !=null \">where id = #{id} </if></script>") public List<User> findUserById(User user);
方式二:
@Mapper public interface MybatisDao { //使用UserDaoProvider类的findUserById方法来生成sql @SelectProvider(type = UserDaoProvider.class, method = "findUserById") public List<User> findUserById(User user); class UserDaoProvider { public String findUserById(User user) { String sql = "SELECT * FROM user"; if(user.getId()!=null){ sql += " where id = #{id}"; } return sql; } } }