mybatis注解开发
一、常用注解
- @Insert
- @Update
- @Delete
- @Select
- @Result 实现结果集封装
- @Results 可以与@Result一起使用,封装多个结果集
- @One 实现一对一结果集封装
- @Many 实现一对多结果集封装
二、简单增删改查
@Insert("insert into user (username) values (#{username})")
public void add(User user);
@Update("update user set username = #{username} where id = #{id}")
public void update(User user);
@Delete("delete from user where id = #{id}")
public void delete(Integer id);
@Select("select * from user")
public List<User> select();
@Select("select * from user where id = #{id}")
public User findById(Integer id);
三、实现复杂映射
- @Results 代替的标签是
<resultMap>
,可以使用单个@Result
,或@Result集合:@Results({@Result(), @Result(), ...})
或@Results({@Result()})
- @Result 代替了
<id>
和<result>
标签- column: 数据库列名
- property: 装配的属性名
- one: 需要使用@One注解
(@Result(one=@One)())
- many: 需要使用@Many注解
(@Result(many=@Many)())
- @One 代替了
<assocation>
标签 - @Many 代替了
<collection>
标签
1.一对一
/**
* @One里可以写sql,也可以引用方法
*/
@Results({
@Result(property = "id", column = "id"),
@Result(property = "orderTime", column = "orderTime"),
@Result(property = "total", column = "total"),
@Result(property = "user", column = "uid", javaType = User.class,
one = @One(select = "com.example.demo.mapper.AnnoUserMapper.findById"))
})
@Select("select * from orders")
public List<Order> findOrderAndUser();
2.一对多
@Select("select * from user")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "orderList", column = "id", javaType = List.class,
many = @Many(select = "com.example.demo.mapper.AnnoOrderMapper.findOrderByUid"))
})
public List<User> findAll();
3.多对多
类似一对多
示例代码见:https://gitee.com/ixinglan/mybatis-tec.git