Mybatis注解:

常用的注解:

常用注解有:

@Select :查询相关的SQL写在@Select注解中,花括号里面的内容可以是字符串也可以是字符串数组。

@Select({"select id,username,phone from db_user where id = #{key}"})
User selectUserByPrimaryKey(Long key);

@SelectKey:

@SelectKey(statement = "select last_insert_id()" ,keyProperty = "id",keyColumn = "id",resultType = int.class,before = false) 
public int insert(User user);

@Insert

@Insert({"insert into db_user(username, password, nickname, phone, email) values (#{username}, #{password}, #{nickname}, #{phone}, #{email})"})
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);

SQL写在@Insert注解中,花括号里面的内容可以是字符串也可以是字符串数组。当添加操作需要返回自增主键时可以使用@Options注释。添加属性useGeneratedKeys = truekeyProperty = "id"即可在数据添加后获取添加数据的ID值。

@Update

@Update({"update db_user set name = #{name} where id = #{id}"})
int updateUserByPrimaryKey(User user);

修改相关的SQL写在@Update注解中,花括号里面的内容可以是字符串也可以是字符串数组。

@Delete

@Delete({"delete from db_user where id = #{key}"})
int deleteUserByPrimaryKey(Long key);

删除相关的SQL写在@Delete注解中,花括号里面的内容可以是字符串也可以是字符串数组。

@Result

@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);

@Results和@Result注解是结合起来用的,@Result注解包含在@Results注解的value属性中。

@Results

@Results 注解有两个属性,分别是id和value。其中id属性对应的是XML配置中resultMap标签的id属性,这样只要在接口中写一次就可以公用一个resultMap了。而value属性对应的是XML配置中resultMap标签下的<id>和<result>标签,<id>标签用id=true属性来确定。

@ResultMap

注解就一个作用,使用已经定义好的@Results或XML配置里已经写好的resultMap。里面的value属性即是@Results的id属性值或XML里resultMap的id属性值。

@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="com.breivty.mappers.AddressMapper.getAddress"))  
})  
public List<Student> getAllStudents();

@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="com.brevity.mappers.StudentMapper.getStudentsByClassId"))  
    })  
public Class getClass(int id);

  • 21
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值