Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of plus conditional Constructor in MyBatis

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of the plus conditional constructor in MyBatis. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Conditional constructor description

The following first input parameter boolean condition indicates whether the condition is added to the last generated SQL, for example:

Query.like (StringUtils.isNotBlank (name), Entity::getName, name) .eq (Entity::getAge, age)

Several methods in the following code block are used to complete the input parameters of individual boolean types from top to bottom, and the default is true, such as:

The following generic Param is a subclass instance of Wrapper (with all methods of AbstractWrapper)

The R that appears in the input parameter of the following method is generic, String in normal wrapper, and function in LambdaWrapper (for example, Entity::getId,Entity is entity class, getId is getMethod of field id)

The R column in the input parameters of the following method represents the database field, and when the specific type of R is String, it is the database field name (the field name is wrapped by the escape character of the database keyword!)! Instead of entity class data field name!!, and when R specific type is SFunction, project runtime does not support eclipse's own compiler!!

The following examples are the use of ordinary wrapper, input parameters for Map and List are expressed in the form of json!

If the Map or List of the input parameter is empty in use, it will not be added to the final generated sql!

Warning

Do not support and disapprove of transferring Wrapper in RPC calls:

Wrapper is very heavy.

Transmitting wrapper can be compared to your controller receiving value with map (develop on a whim, maintain the crematorium)

The correct RPC calling posture is to write a DTO for transmission, and the callee performs the corresponding operation according to the DTO.

We refuse to accept any issue or even pr related to RPC transmission Wrapper error reporting

AbstratWrappr

Description

Parent classes of QueryWrapper (LambdaQueryWrapper) and UpdateWrapper (LambdaUpdateWrapper)

The where condition used to generate sql, and the entity attribute is also used to generate the where condition of sql

Note: there is no association between the where conditions generated by entity and the where conditions generated using each api

:::

AllEqallEq (Map params) allEq (Map params, boolean null2IsNull) allEq (boolean condition, Map params, boolean null2IsNull)

All eq (or individual isNull)

Tip individual parameters description:

Params: key is the database field name, and value is the field value

Null2IsNull: if true, call the isNull method when the value of map is null, and ignore the null if value is false.

Example 1: allEq ({id:1,name: "Lao Wang", age:null})-> id = 1 and name = 'Lao Wang' and age is null

Example 2: allEq ({id:1,name: "Lao Wang", age:null}, false)-> id = 1 and name = 'Lao Wang'

AllEq (BiPredicate filter, Map params) allEq (BiPredicate filter, Map params, boolean null2IsNull) allEq (boolean condition, BiPredicate filter, Map params, boolean null2IsNull) individual parameter description

Filter: filter function, whether to allow fields to be passed into the comparison condition

Params and null2IsNull: ditto

Example 1: allEq ((kpene v)-> k.indexOf ("a") > = 0, {id:1,name: "Lao Wang", age:null})-> name = 'Lao Wang' and age is null case 2: allEq ((KPere v)-> k.indexOf ("a") > = 0, {id:1,name: "Lao Wang", age:null}, false)-> name = 'Lao Wang'

Eq

Equal to =

Eq (R column, Object val) eq (boolean condition, R column, Object val) instance

Eq ("name", "Lao Wang")-> name = 'Lao Wang'

Nene (R column, Object val) ne (boolean condition, R column, Object val)

Not equal to

Example: ne ("name", "Lao Wang")-> name 'Lao Wang'

Gtgt (R column, Object val) gt (boolean condition, R column, Object val)

Greater than >

Example: gt ("age", 18)-> age > 18

Gege (R column, Object val) ge (boolean condition, R column, Object val)

Greater than or equal to > =

Example: ge ("age", 18)-> age > = 18

Ltle (R column, Object val) le (boolean condition, R column, Object val)

Less than age

< 18 lele(R column, Object val)le(boolean condition, R column, Object val) 小于等于 age age between 18 and 30 notBetweennotBetween(R column, Object val1, Object val2)notBetween(boolean condition, R column, Object val1, Object val2) NOT BETWEEN 值1 AND 值2 例: notBetween("age", 18, 30)->

Age not between 18 and 30

Likelike (R column, Object val) like (boolean condition, R column, Object val)

LIKE'% value%'

Example: like ("name", "Wang")-> name like'% Wang%'

NotLikenotLike (R column, Object val) notLike (boolean condition, R column, Object val)

NOT LIKE'% value%'

Example: notLike ("name", "Wang")-> name not like'% Wang%'

LikeLeftlikeLeft (R column, Object val) likeLeft (boolean condition, R column, Object val)

LIKE'% value'

Example: likeLeft ("name", "Wang")-> name like'% Wang'

LikeRightlikeRight (R column, Object val) likeRight (boolean condition, R column, Object val)

LIKE 'value'

Example: likeRight ("name", "Wang")-> name like 'Wang%'

IsNullisNull (R column) isNull (boolean condition, R column)

Field IS NULL

Example: isNull ("name")-> name is null

IsNotNullisNotNull (R column) isNotNull (boolean condition, R column)

Field IS NOT NULL

Example: isNotNull ("name")-> name is not null

In

Field IN (value.get (0), value.get (1), …)

In (R column, Collection value) in (boolean condition, R column, Collection value) example

In ("age", {1rem 2pr 3})-> age in (1pm 2p3)

In (R column, Object...) Values) in (boolean condition, R column, Object... Values)

Field IN (v0, v1, …)

Example

In ("age")-> age in (1pm 2p3)

NotInnotIn (R column, Collection value) notIn (boolean condition, R column, Collection value)

Field NOT IN (value.get (0), value.get (1), …)

Example: notIn ("age", {1pm 2pm 3})-> age not in (1pm 2pm 3)

NotIn (R column, Object...) Values) notIn (boolean condition, R column, Object... Values)

Field NOT IN (v0, v1, …)

Example: notIn ("age", 1mem2jin3)-> age not in (1min2pyr3)

InSqlinSql (R column, String inValue) inSql (boolean condition, R column, String inValue)

Field IN (sql statement)

Example: inSql ("age")-> age in (1 mine2, 3, 4, 5)-> age in

Example: inSql ("id", "select id from table where id")

< 3")->

Id in (select id from table where id

< 3) notInSqlnotInSql(R column, String inValue)notInSql(boolean condition, R column, String inValue) 字段 NOT IN ( sql语句 ) 例: notInSql("age", "1,2,3,4,5,6")->

Age not in (1, 2, 3, 4, 5, 6)

Example: notInSql ("id", "select id from table where id")

< 3")->

Id not in (select id from table where id

< 3) groupBygroupBy(R... columns)groupBy(boolean condition, R... columns) 分组:GROUP BY 字段, … 例: groupBy("id", "name")->

Group by id,name

OrderByAsc

Sort: ORDER BY field, … ASC

OrderByAsc (R... Columns) orderByAsc (boolean condition, R... Columns) instance

OrderByAsc ("id", "name")-> order by id ASC,name ASC

OrderByDescorderByDesc (R... Columns) orderByDesc (boolean condition, R... Columns)

Sort: ORDER BY field, … DESC

Example: orderByDesc ("id", "name")-> order by id DESC,name DESC

OrderByorderBy (boolean condition, boolean isAsc, R... Columns)

Sort: ORDER BY field, …

Example: orderBy (true, true, "id", "name")-> order by id ASC,name ASC

Havinghaving (String sqlHaving, Object... Params) having (boolean condition, String sqlHaving, Object... Params)

HAVING (sql statement)

Example: having ("sum (age) > 10")-> having sum (age) > 10

Example: having ("sum (age) > {0}", 11)-> having sum (age) > 11

Funcfunc (Consumer consumer) func (boolean condition, Consumer consumer)

Func method (mainly convenient in the emergence of if. Else can be continuously chained with different methods)

Example: func (I-> if (true) {i.eq ("id", 1)} else {i.ne ("id", 1)})

Oror () or (boolean condition)

Splicing OR

: tip Note:

An active call to or means that the next method is not connected with and! (if you do not call or, it defaults to using and connection)

:::

Example: eq ("id", 1). Or (). Eq ("name", "Lao Wang")-> id = 1 or name = 'Lao Wang'

Or (Consumer consumer) or (boolean condition, Consumer consumer)

OR nesting

Example: or (I-> i.eq ("name", "Li Bai"). Ne ("status", "alive")-> or (name ='Li Bai 'and status' alive')

Andand (Consumer consumer) and (boolean condition, Consumer consumer)

AND nesting

Example: and (I-> i.eq ("name", "Li Bai"). Ne ("status", "alive")-> and (name ='Li Bai 'and status' alive')

Nestednested (Consumer consumer) nested (boolean condition, Consumer consumer)

Normal nesting without AND or OR

Example: nested (I-> i.eq ("name", "Li Bai"). Ne ("status", "alive")-> (name ='Li Bai 'and status' alive')

Apply- splicing SQLapply (String applySql, Object...) Params) apply (boolean condition, String applySql, Object... Params)

This method can be used in database functions.

The params of the dynamic input parameter corresponds to the {index} part of the previous applySql. There will be no risk of sql injection, otherwise there will be!

Example

Apply ("id = 1")-> id = 1

Example: apply ("date_format (dateColumn,'%Y-%m-%d') = '2008-08-08'")-> date_format (dateColumn,'%Y-%m-%d') = '2008-08-08') example: apply ("date_format (dateColumn,'%Y-%m-%d') = {0}", "2008-08-08")-> date_format (dateColumn,'%Y-%m-%d') = '2008-08-08' ")

Lastlast (String lastSql) last (boolean condition, String lastSql)

Ignore the optimization rules and connect directly to the end of sql.

: tip Note:

Can only be called once, and multiple calls are subject to the last call.

There is a risk of sql injection, please use it with caution

:::

Example: last ("limit 1")

Existsexists (String existsSql) exists (boolean condition, String existsSql)

Concatenate EXISTS (sql statement)

Example: exists ("select id from table where age = 1")-> exists (select id from table where age = 1)

NotExistsnotExists (String notExistsSql) notExists (boolean condition, String notExistsSql)

Concatenate NOT EXISTS (sql statement)

Example: notExists ("select id from table where age = 1")-> not exists (select id from table where age = 1)

QueryWrapper

: tip description:

Inherited from AbstractWrapper, its own internal attribute entity is also used to generate where conditions

And LambdaQueryWrapper, which can be obtained through the new QueryWrapper (). Lambda () method

:::

Selectselect (String... SqlSelect) select (Predicate predicate) select (Class entityClass, Predicate predicate)

Set query field

: tip description:

The above methods are divided into two categories.

The second method is to filter the query field (except the primary key). The entity attribute in wrapper is required to have a value before the input parameter does not contain class.

These two types of methods are called repeatedly for the last time.

:::

Example: select ("id", "name", "age")

Example: select (I-> i.getProperty () .startsWith ("test"))

UpdateWrapper

: tip description:

Inherited from AbstractWrapper, its own internal attribute entity is also used to generate where conditions

And LambdaUpdateWrapper, which can be obtained through the new UpdateWrapper (). Lambda () method!

:::

Setset (String column, Object val) set (boolean condition, String column, Object val)

SQL SET field

Example: set ("name", "Lao Li Tou")

Example: set ("name", ")-> database field value becomes an empty string

For example: set ("name", null)-> database field value becomes null

SetSqlsetSql (String sql)

Set SET partial SQL

Example: setSql ("name = 'Lao Li Tou'")

Lambda

Get LambdaWrapper

In QueryWrapper is to get LambdaQueryWrapper

In UpdateWrapper is to get LambdaUpdateWrapper

Use Wrapper to customize SQL

: tip Note:

Mybatis-plus version required > = 3.0.7

The param parameter name is either ew or annotated @ Param (Constants.WRAPPER)

Use ${ew.customSqlSegment}

Entity in Wrapper is not supported to generate where statements

:::

Best practices for kotlin persistent object definition

Because kotlin has more data objects (data class) than java, it may be mixed in unspecified cases. It is recommended that you define persistent objects in the following form

TableName ("sys_user") class User {@ TableId (type = IdType.AUTO) var id: Int? = null @ TableField ("username") var name: String? = null var roleId: Int? = null}

Note: TableId and TableField are not necessary here, just to demonstrate the use of annotation in Mybatis-Plus

Here all members need to be defined as nullable types (?) and given the initial value of null so that we can use it in the following scenarios (similar to updateSelective in java)

Val wrapper = KtUpdateWrapper (User::class.java) .eq (User::id, 2) val newRecord = User () newRecord.name = "newName" userMapperkeeper updated .update (newRecord, wrapper)

It is not recommended to use data class and full-parameter construction methods, so we will write a lot of unnecessary null to construct an empty object

Use the annotation @ Select ("select * from mysql_data ${ew.customSqlSegment}") List getAll (@ Param (Constants.WRAPPER) Wrapper wrapper); use XMLList getAll (Wrapper ew); SELECT * FROM mysql_data ${ew.customSqlSegment} chain call lambda / / distinguish: / / chain call normal UpdateChainWrapper update (); / chain call lambda type. Note: Kotlin LambdaUpdateChainWrapper lambdaUpdate () is not supported; / / equivalent example: query (). Eq ("id", value). One (); lambdaQuery (). Eq (Entity::getId, value). One (); / / equivalent example: update (). Eq ("id", value). Remove (); lambdaUpdate (). Eq (Entity::getId, value). Remove () This is the end of this article on "sample Analysis of plus conditional Constructor in MyBatis". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report