Mybatis written annotations (with more than 10 conventional example)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/sunnyzyq/article/details/102533764

[Introduction]

Mybatis In addition to writing XML configuration, you can also use written notes.

First, the need to introduce rely Mybatis:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.1.3</version>
</dependency>

Then marked with the corresponding notes on the interface @Mapper

 

The following are common Myatis notes written:

[1] New objects (non-increment ID)

When inserted, the value of the database field with the value of the object will automatically match the name of the attribute.

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

[2] new objects (increment ID)

If the database user id table is self-growth, we can add @Options comment, then the object after insertion, id property will automatically get to the primary key.

The primary key field @Options (useGeneratedKeys = true, keyProperty = "id") id of the database table in which.

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

[3] According to the query object ID

 @Param (value = "id") wherein the SQL statement corresponding to the id # {id}

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

In the process the query object, table fields automatically to packing the same name attribute. Of course, it can also be written binding form.

As follows: @Result annotation object property field, column is a table field.

@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
	@Result(property="id", column="id"),
	@Result(property="name", column="name"), 
	@Result(property="age", column="age"), 
	@Result(property="remark", column="remark"), 
})
public User getUserById(@Param(value = "id") long id);

[4] greater than (>) Queries

In the SQL statement, the direct writing>, but in xml, usually greater than escape  & gt; Alternatively (see 6.2 xml written description).

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

[5] of less than (<) Query

In the SQL statement, the direct writing <but in xml, usually less than escaped  & lt; Alternatively (see 6.2 xml written description).

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

[6] IN keyword query

(6.1) with the IN subquery

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

(6.2) of a set of queries IN

List collections, Set collections, arrays are applicable.

Note: @Select ({ "<Script>", "XX1", "XX2", "</ Script>"}) The wording of xml writing mode. All SQL are in the <script> </ script> This labels, including label is a pair of braces, <script> tags within all the parameters will be automatically stitching when the last execution of SQL, as here xx1xx2, to forth. <script> tag may also be embedded within a tag, such as the following in the <foreach>, all tags within quotes are single quotes.

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

In Postgrelsql, the IN and if the same SQL ANY logic semantics, then try to use ANY, it will be more efficient. Such as:

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

[7] LIKE keyword query

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

[8] time of the query

(8.1) Date Type: Direct incoming Compare

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

(8.2) String Type: needs to be translated (they need time precision press clipping)

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' )

Such as Mysql writing:

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

[9] advanced queries (dynamic SQL)

 Note: [& gt;] is greater than (>) escape, [& lt;] is less than (<) escape

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

[10] modifying objects

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

[11] deleting objects

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

 

Guess you like

Origin blog.csdn.net/sunnyzyq/article/details/102533764