mybatis映射常用注解

    科技2022-08-31  117

    面对注解的resultmap,我有点陌生于是找了点资料

    1、结果集映射2、关系映射 这玩意叫做结果集映射

    1、结果集映射

    @Result,@Results,@ResultMap是结果集映射的三大注解。

    首先说明一下@Results各个属性的含义,id为当前结果集声明唯一标识,value值为结果集映射关系,@Result代表一个字段的映射关系,column指定数据库字段的名称,property指定实体类属性的名称,jdbcType数据库字段类型,@Result里的id值为true表明主键,默认false;使用@ResultMap来引用映射结果集,其中value可省略。

    声明结果集映射关系代码:

    @Select({"select id, name, class_id from student"}) @Results(id="studentMap", value={ @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true), @Result(column="name", property="name", jdbcType=JdbcType.VARCHAR), @Result(column="class_id ", property="classId", jdbcType=JdbcType.INTEGER) }) List<Student> selectAll();

    引用结果集代码:

    @Select({"select id, name, class_id from student where id = #{id}"}) @ResultMap(value="studentMap") Student selectById(integer id);

    这样就不用每次需要声明结果集映射的时候都复制冗余代码,简化开发,提高了代码的复用性。

    2、关系映射

    3.1、@one注解:用于一对一关系映射

    @Select("select * from student") @Results({ @Result(id=true,property="id",column="id"), @Result(property="name",column="name"), @Result(property="age",column="age"), @Result(property="address",column="address_id",one=@One(select="cn.mybatis.mydemo.mappers.AddressMapper.getAddress")) }) public List<Student> getAllStudents();

    3.2、@many注解:用于一对多关系映射

    @Select("select * from t_class where id=#{id}") @Results({ @Result(id=true,column="id",property="id"), @Result(column="class_name",property="className"), @Result(property="students", column="id", many=@Many(select="cn.mybatis.mydemo.mappers.StudentMapper.getStudentsByClassId")) }) public Class getClass(int id);
    Processed: 0.008, SQL: 10