【java框架】MyBatis(7)--MyBatis註解開發

1.MyBatis註解開發

1.1.Lombok的基本使用

Lombok是SpringBoot2.1.X版本與IDEA官方支持的一個插件,它是爲簡化POJO類中繁雜重複代碼:geter/setter/toString/hashcode/equals等,提供了一種java

全註解的方式來簡化咱們平常項目中的代碼,現在在SpringBoot與微服務項目中,Lombok是一款很是流行的插件,使用瞭解它能夠提升咱們平常的開發效率。git

 

Lombok的使用很是簡單:github

①首先須要在IDEA的Settings-Plugins中去下載並安裝Lombok的應用插件:sql

 

②在Maven項目中引入Lombok的依賴包:mybatis

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

Lombok的scope=provided,說明它只在編譯階段生效,不須要打入包中。事實正是如此,Lombok在編譯期將帶Lombok註解的Java文件正確編譯爲完整的Class文件。app

 

③在IDEA中設置開啓對Lombok的註解Anno支持:ide

 

開啓該項是爲了讓Lombok註解在編譯階段起到做用。微服務

 

④在項目中的POJO類中使用Lombok的註解開發:ui

 

平常項目中比較經常使用的高頻率註解:spa

  • @Data:做用於類上,是如下註解的集合:@ToString @EqualsAndHashCode @Getter @Setter @RequiredArgsConstructor;
  • @NoArgsConstructor:生成無參構造器;
  • @AllArgsConstructor:生成全參構造器;
  • @Log:做用於類上,生成日誌變量。針對不一樣的日誌實現產品,有不一樣的註解

 

1.2.Mybatis經常使用註解

  • @Select:實現查詢
  • @Insert:實現插入
  • @Update:實現更新
  • @Delete:實現刪除
  • @Result:實現結果集封裝
  • @Results:能夠與@Result連用,封裝多個結果集
  • @One:一對一關係結果封裝
  • @Many:多對1、多對多結果封裝

 

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

相關文章
相關標籤/搜索