古道长亭

Contact me with ixiaoqiang0011@gmail.com


  • 首页

  • 归档

  • 分类

  • 关于

  • Book

  • 搜索

mybatis注解开发

时间: 2022-08-07   |   分类: mybatis   | 字数: 543 字 | 阅读约: 2分钟 | 阅读次数:

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

#mybatis#
QQ扫一扫交流

标题:mybatis注解开发

作者:古道长亭

声明: 欢迎加群交流!

如有帮助,欢迎多多交流 ^_^

微信打赏

支付宝打赏

mybatis缓存
mybatis复杂映射
  • 文章目录
  • 站点概览
古道长亭

古道长亭

Always remember that your present situation is not your final destination. The best is yet to come.

226 日志
57 分类
104 标签
GitHub Gitee
友情链接
  • 古道长亭的BOOK
  • JAVA学习
标签云
  • Mysql
  • 搜索引擎
  • Mybatis
  • 容器
  • 架构
  • 消息队列
  • Flink
  • Sharding sphere
  • 流处理
  • 缓存
  • 一、常用注解
  • 二、简单增删改查
  • 三、实现复杂映射
    • 1.一对一
    • 2.一对多
    • 3.多对多
© 2019 - 2024 京ICP备19012088号-1
0%