mybatis注解

参考  https://mybatis.org/mybatis-3/zh/java-api.html

mybatis可以不使用xml做映射文件,使用 @Mapper 标注的Mapper接口,在Mapper接口中使用mybatis的注解,然后在mybatis配置文件中的<mappers>下注册这个接口类,常用注解说明:

  • @Insert, @Select,@Delete,@Update ,对应标签<insert>,<select>,<delete><update>,和对应标签的作用相同

    • 属性value为sql语句

  • @Param,接口方法参数超过1个时,需要用@Param给每个参数设置别名

    • 属性value为别名

  • @ResultType,为 @Select 或者 @SelectProvider 注解的方法指定结果对象类型似<select>中的resultType属性

    • 属性value为POJO类

  • @ResultMap,为 @Select 或者 @SelectProvider 注解的方法指定结果集合的id,类似<select>中的resultMap属性

    • 属性value为结果集合id,可以使@Results设置的,也可以来自xml映射文件

  • @Results,接口方法的返回值设置为结果集合(或返回一个对象,有多个属性)

    • 属性id,设置结果集合id,可使用@ResultMap复用

    • 属性value,为@Result 注解的数组

  • @Result,给表字段和对象属性做映射,属性:idcolumnjavaTypejdbcTypetypeHandleronemany

    • 属性id,布尔值,表明是否是表的主键

    • 属性one,等于@One注解,和 <association> 类似

    • 属性many,等于@Many注解,和<collection>类似

  • @One,和 <association> 类似,一对一或多对一的查询

    • 属性select,和 <association>的select属性类似,为statement的id(接口全限定名.方法名)

    • 属性fetchType,枚举类FetchType的值,指定是否懒加载

  • @Many,和<collection>类似,一对多或多对多的查询,属性和@One相同

  • @SelectKey,与<selectKey>功能相同。该注解只能在 @Insert@InsertProvider@Update@UpdateProvider 标注的方法上使用,用来获取主键

    • 属性statement = "select last_insert_id()",其他属性和<selectKey>相同

  • @InsertProvider,@SelectProvider,@UpdateProvider,@DeleteProvider,为接口方法提供sql执行语句

    • 属性type,指定提供sql语句的类

    • 属性method,指定提供sql语句的方法

  • //SQL语句提供类
    public class CatProvider {
        public  String query(){
            return "select * from cat where id=#{id}";
        }
    }
    //Mapper接口
    @Mapper
    public interface CatMapper {
        @SelectProvider(type = CatProvider.class,method = "query")
        @ResultType(Cat.class)
        Cat providerQuery(int id) throws Exception;
    }
    //测试类
    public class CatTest {
        @Test
        public void test1(){
            SqlSession sqlSession= MybatisUtil.getSqlSession();
            CatMapper catMapper=sqlSession.getMapper(CatMapper.class);
            try {
                System.out.println(catMapper.providerQuery(2));
                sqlSession.commit();
            } catch (Exception e) {
                e.printStackTrace();
                sqlSession.rollback();
            }finally {
                MybatisUtil.closeSqlSession();
            }
        }
    }
  • 动态SQL,在@Insert, @Select,@Delete,@Update属性中使用<script>包裹sql语句,sql语句中就可以使用<set> <when> <if> <foreach> 等标签

@Select("<script>
" +
        "select * from cat
" +
        "<where>
" +
        "<if test="name!=null"> name=#{name} </if>
" +
        "<if test="age!=null"> and age=#{age} </if>
" +
        "</where>
" +
        "</script>")
@ResultType(Cat.class)
Cat dynamic(@Param("name") String name,@Param("age") Integer age) throws Exception;
  • @InsertProvider,@SelectProvider,@UpdateProvider,@DeleteProvider的动态SQL,太复杂,推荐使用xml配置

原文地址:https://www.cnblogs.com/yjh1995/p/13893798.html