Mybatis註解寫法 Mybatis 註解寫法( 附10餘個常用例子 )

Mybatis 註解寫法( 附10餘個常用例子 )

【前言】

Mybatis 除了 XML 配置寫法,還可以使用註解寫法。

首先需要引入 Mybatis 的依賴:

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>1.3.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>tk.mybatis</groupId>
  8. <artifactId>mapper-spring-boot-starter</artifactId>
  9. <version>1.1.3</version>
  10. </dependency>

然後在接口上打上對應 @Mapper 註解

 

下面是常用的 Myatis 註解寫法:

【1】新增對象( 非自增 ID )

插入的時候,數據庫的值字段會自動匹配對象中同名稱屬性的值。

  1. @Insert(value = { "INSERT INTO user (id, name, age, remark) VALUES (#{id}, #{name}, #{age}, #{remark})" })
  2. public void addUser(User user);

【2】新增對象( 自增 ID )

如果數據庫user表的 id 是自增長,我們可以加上 @Options 註解,那麼該對象在插入後,id 屬性會自動獲取到主鍵。

@Options(useGeneratedKeys=true, keyProperty="id") 其中的 id 對應數據庫表中的主鍵字段。

  1. @Insert(value = { "INSERT INTO user (name, age, remark) VALUES (#{name}, #{age}, #{remark})" })
  2. @Options(useGeneratedKeys=true, keyProperty="id")
  3. public void insertUser(User user);

【3】根據 ID 查詢對象

 @Param(value = "id") 其中的 id 對應 SQL 語句中的 #{id}

  1. @Select("SELECT * FROM user WHERE id = #{id}")
  2. public User getUserById(@Param(value = "id") long id);

在查詢對象的過程中,表字段會自動裝箱給同名屬性。當然,也可以寫成綁定形式。

如下:@Result 註解中 property 是對象字段,column 是表字段。

  1. @Select("SELECT * FROM user WHERE id = #{id}")
  2. @Results({
  3. @Result(property="id", column="id"),
  4. @Result(property="name", column="name"),
  5. @Result(property="age", column="age"),
  6. @Result(property="remark", column="remark"),
  7. })
  8. public User getUserById(@Param(value = "id") long id);

【4】大於 ( > ) 查詢

在SQL 語句中,直接寫作 > ,但在 xml 中,大於通常用轉義 &gt; 替代 ( xml 寫法介紹詳見 6.2)。

  1. @Select("SELECT * FROM user WHERE age > #{age}")
  2. public List<User> getUserList(@Param(value = "age") Integer age);

【5】小於 ( < ) 查詢

在SQL 語句中,直接寫作 < ,但在 xml 中,小於通常用轉義 &lt; 替代  ( xml 寫法介紹詳見 6.2)。

  1. @Select("SELECT * FROM user WHERE age < #{age}")
  2. public List<User> getUserList(@Param(value = "age") Integer age);

【6】IN 關鍵字查詢

(6.1)帶 IN 的子查詢

  1. @Select("SELECT * FROM user WHERE id IN (SELECT id FROM user WHERE name = #{name})")
  2. public List<User> getUserList(@Param(value = "name") String name);

(6.2)帶 IN 的集合查詢

List 集合,Set集合,數組 都適用。

注意:@Select({"<script>", "xx1", "xx2", "</script>"}) 這種寫法爲 xml 方式寫法。所有 SQL 都在 <script> </script> 這對標籤之中,標籤之外是一對大括號,<script> 標籤內的所有參數在最後執行 SQL 的時候會自動拼接,如這裏爲 xx1xx2,以此類推。 <script> 標籤內還可以內嵌標籤,比如下面裏的 <foreach>,標籤內所有引號都爲單引號。

  1. @Select({"<script>", "SELECT * FROM user WHERE id IN ",
  2. "<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach>", "</script>"})
  3. public List<User> getUserList(@Param(value = "ids") List<Long> ids);

在 Postgrelsql 中,如果邏輯SQL中的 IN 和 ANY 的語義相同,那麼儘量用 ANY,這樣會更加效率。如:

  1. @Select("SELECT * FROM user WHERE id = ANY(#{ids}::integer[])")
  2. public List<SubOrderPO> getUserList(@Param(value = "ids") Integer[] ids);

【7】LIKE 關鍵字查詢

  1. @Select("SELECT * FROM user WHERE name LIKE concat('%', #{name}, '%') ")
  2. public List<User> getUserList(@Param(value = "name") String name);

【8】時間查詢

(8.1)Date 類型:直接傳入進行比較

  1. @Select("SELECT * FROM user WHERE create_time > #{createTime}")
  2. public List<User> test(@Param(value = "createTime") Date createTime);

(8.2)String 類型:需要將其轉化( 時間精度可以按自己需要裁取 )

Mysql :STR_TO_DATE('2008-08-08 08:08:08', '%Y-%m-%d %H:%i:%s')

Postgrelsql :to_timestamp('2008-08-08 08:08:08','yyyy-MM-dd hh24:mi:ss')

Oracle : to_date( '2008-08-08 08:08:08' , 'yyyy-MM-dd HH24:mi:ss' )

如 Mysql 寫法:

  1. @Select("SELECT * FROM user WHERE create_time > STR_TO_DATE(#{createTime}, '%Y-%m-%d %H:%i:%s')")
  2. public List<User> test(@Param(value = "createTime") String createTime);

【9】高級查詢( 動態SQL )

 注意:【&gt;】是大於(>)的轉義,【&lt;】 是小於(<)的轉義

  1. @Select({"<script>", "SELECT * FROM user ","<where>",
  2. "<if test = 'name != null' >", " AND name LIKE concat('%', #{name}, '%') ", "</if>",
  3. "<if test = 'age != null and age != 0' >", " AND age &lt; #{age} ", "</if>",
  4. "</where>", "</script>"})
  5. public List<User> getUserList(@Param(value = "name") String name, @Param(value = "age") Integer age);

【10】修改對象

  1. @Update("UPDATE user SET name = #{name} WHERE id = #{id}")
  2. public void update(@Param(value = "id") Long id, @Param(value = "name") String name);

【11】刪除對象

  1. @Delete("Delete FROM user WHERE id = #{id}")
  2. public void delete(@Param(value = "id") Long id);

 

文章最後發佈於: 2019-10-13 19:56:02
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章