• 【java框架】MyBatis(7)--MyBatis注解开发


    1.MyBatis注解开发

    1.1.Lombok的基本使用

    Lombok是SpringBoot2.1.X版本与IDEA官方支持的一个插件,它是为简化POJO类中繁杂重复代码:geter/setter/toString/hashcode/equals等,提供了一种

    全注解的方式来简化我们日常项目中的代码,如今在SpringBoot与微服务项目中,Lombok是一款非常流行的插件,使用了解它可以提高我们日常的开发效率。

    Lombok的使用非常简单:

    ①首先需要在IDEA的Settings-Plugins中去下载并安装Lombok的应用插件:

    ②在Maven项目中引入Lombok的依赖包:

    <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.16.18</version>
          <scope>provided</scope>
    </dependency>

    Lombok的scope=provided,说明它只在编译阶段生效,不需要打入包中。事实正是如此,Lombok在编译期将带Lombok注解的Java文件正确编译为完整的Class文件。

    ③在IDEA中设置开启对Lombok的注解Anno支持:

    开启该项是为了让Lombok注解在编译阶段起到作用。

    ④在项目中的POJO类中使用Lombok的注解开发:

    日常项目中比较常用的高频率注解:

    • @Data:作用于类上,是以下注解的集合:@ToString @EqualsAndHashCode @Getter @Setter @RequiredArgsConstructor;
    • @NoArgsConstructor:生成无参构造器;
    • @AllArgsConstructor:生成全参构造器;
    • @Log:作用于类上,生成日志变量。针对不同的日志实现产品,有不同的注解

    1.2.Mybatis常用注解

    • @Select:实现查询
    • @Insert:实现插入
    • @Update:实现更新
    • @Delete:实现删除
    • @Result:实现结果集封装
    • @Results:可以与@Result连用,封装多个结果集
    • @One:一对一关系结果封装
    • @Many:多对一、多对多结果封装

    1.3.简单增删改查

    非常简单,直接上Mapper注解查询:

    public interface CustomerMapper {
        @Select("select id, name, age, password, birthday from customer")
        List<Customer> selectCustomers();
    
        @Insert("insert into customer values (#{id}, #{name}, #{age}, #{password}, #{birthday})")
        int insert(Customer customer);
    
        @Update("update customer set name = #{name}, password = #{password} where id = #{id}")
        int update(Customer customer);
    
        @Delete("delete from customer where id = #{id}")
        int delete(int id);
    
        @Select("select * from customer where id = #{id}")
        Customer findOneById(int id);
    }

    需要注意的是需要在mybatis-config.xml配置文件中添加对应Mapper所在的类配置:

     <mappers>
            <mapper class="com.fengye.mapper.CustomerMapper"></mapper>
    </mappers>

    1.4.一对一关联查询

    表关系模型:

    顾客与订单号的关系:一个顾客对应多个订单,一个订单从属于一个顾客。

     

    设计查询思路:从一方出发,查询商品订单同时,根据当前的uid查询出当前订单对应的顾客。

    对应Mapper接口及相应配置:

    public interface OrderMapper {
        /**
         * 一对一:订单对应一个客户
         * @return
         */
        @Select("select * from orders")
        @Results(value = {
                @Result(column = "id", property = "id", id = true),
                @Result(column = "ordertime", property = "orderTime"),
                @Result(column = "total", property = "total"),
                @Result(column = "price", property = "price"),
                @Result(property = "customer", one = @One(select = "com.fengye.mapper.CustomerMapper.findOneById"), column = "uid")
        })
        List<Orders> selectAll();
    
        @Select("select * from orders where uid = #{uid}")
        List<Orders> findByUid(@Param("uid") int id);
    }
    
    
    public interface CustomerMapper {
        @Select("select * from customer where id = #{id}")
        Customer findOneById(int id);
    }

    因为使用到了两个Mapper接口中的方法,所以需要引入对应的两个Mapper接口类:

     <mappers>
            <mapper class="com.fengye.mapper.CustomerMapper"></mapper>
            <mapper class="com.fengye.mapper.OrderMapper"></mapper>
    </mappers>

    1.5.一对多关联查询

    相反,对应一个顾客的订单可能是多个,那么从顾客角度分析,顾客与订单的关系就是一对多关系。

    相应的查询设计思路:

    封装对应的Mapper注解查询接口如下:

    public interface CustomerMapper {
        @Select("select * from customer")
        @Results({
                @Result(property = "id", column = "id", id = true),
                @Result(property = "name", column = "name"),
                @Result(property = "age", column = "age"),
                @Result(property = "password", column = "password"),
                @Result(property = "birthday", column = "birthday"),
                @Result(property = "ordersList", many = @Many(select = "com.fengye.mapper.OrderMapper.findByUid"),
                        column = "id", javaType = List.class)
        })
        List<Customer> selectAllList();
    }
    
    public interface OrderMapper {
        @Select("select * from orders where uid = #{uid}")
        List<Orders> findByUid(@Param("uid") int id);
    }

    1.6.多对多关联查询

    多对多最经典的还是用户与角色的关系,一个用户对应多个角色,一个角色可以对应多个用户。

    查询设计思路:

    可以从角色入手,也可以从用户入手,在设计POJO时对应在多方肯定有一个集合的属性字段,假设从用户角度出发,设计查询语句如下:

    对应的Mapper接口层注解封装如下:

    public interface UserMapper {
        /**
         * 查询出所有用户及其对应的角色
         * @return
         */
        @Select("select * from sys_user")
        @Results({
                @Result(property = "id", column = "id", id = true),
                @Result(property = "username", column = "username"),
                @Result(property = "password", column = "password"),
                @Result(property = "birthday", column = "birthday"),
                @Result(property = "roleList", many = @Many(select = "com.fengye.mapper.RoleMapper.findRoleListByUid"),
                column = "id", javaType = List.class)
        })
        List<User> findAllUserRole();
    }
    
    public interface RoleMapper {
        @Select("select * from sys_role r, sys_user_role ur where r.id = ur.roleId and ur.userId = #{uid}")
        List<Role> findRoleListByUid(@Param("uid") int uid);
    }

    注解开发优缺点:

    注解开发相对于传统的xml可以在实际项目中一定程度的减少大量的xml配置,针对于基础简单的sql语句非常实用;

    但是注解开发并不能完全替代xml,比如动态sql使用<if>条件查询等复杂sql的场景,最好还是使用xml。

    本博客写作参考文档:

    https://www.jianshu.com/p/2543c71a8e45  《Lombok的基本使用》

    https://www.bilibili.com/video/BV1XV411e7hm?p=30  《Mybatis注解开发》

    示例代码已上传至Github地址:

    https://github.com/devyf/MyBatisReview/tree/master/fengye_mybatis_annotation

  • 相关阅读:
    2019.10.11CSS
    2019.10.11 THML
    虚拟机FAQ
    thinkpad安装虚拟机 开启虚拟功能要在bios的security里面设置
    JDK在windows系统下环境变量的设置
    有关operamasks-ui的一些信息汇总
    从用List给ArrayList赋值看容器的传值,最好用.addAll
    给eclipse安装svn插件
    Java接口 枚举型Enumeration
    linux下的grep命令
  • 原文地址:https://www.cnblogs.com/yif0118/p/14427498.html
Copyright © 2020-2023  润新知