编程知识 cdmana.com

Mybatis's four magic tricks, don't step on the pit!

1、 stay Mybatis mapping.xml Larger than the mapping file used in the configuration file > Sign less than sign <

because Mybatis The mapping file follows xml File format , So you can't use things like the greater than sign or the less than sign xml File special characters , You need to use escape characters instead of .

<

<

Less than no.

More than no.

&

&

and

'

Single quotation marks

"

Double quotes

have access to :

SELECT * FROM test 
WHERE 1 = 1 AND start_date  &lt;= CURRENT_DATE AND end_date &gt;= CURRENT_DATE
<![CDATA[ when min(starttime)<='12:00' and max(endtime)<='12:00' ]]> 

2、Mybatis Use in OGNL expression test Compare strings

stay Mybatis In the mapping profile , Use OGNL expression test When , When comparing strings , Need to call toString() The method guarantees == The values on both sides are String type .

<!--  The following is a mistake , Flip a NumberFormatException abnormal  -->
<if test="username == 'U'">

<!--  The correct way to write it is as follows  -->
<if test="username == 'U'.toString()">
<if test='username == "U"'> 

3、Mybatis Realization WHERE IN Inquire about

WHERE IN Querying ,IN Is a list , You need to pass a list parameter , Use foreach Realization .

<select id="selectPostIn" resultType="domain.blog.Post">
 SELECT * FROM POST P
 WHERE ID in
 <foreach item="item" index="index" collection="list"  open="(" separator="," close=")">
    #{item}
 </foreach>
</select> 

When using iteratable objects or arrays ,index Is the number of current iterations ,item The value of is the element obtained in this iteration . When using a dictionary ( perhaps Map.Entry A collection of objects ) when ,index It's a key ,item Is the value .

You can put any iteratable object ( As listing 、 Collection etc. ) And any dictionary or array object passed to foreach As a set parameter .

4、Mybatis When inserting data, the primary key of the inserted record is returned id

In the case of input library insertion , If we need to use the primary key of the inserted record , You need to return the primary key of the data you just inserted id.

By setting insert Labeled useGeneratedKeys The attribute is true Can return the primary key of the inserted record id.

<insert id="User" useGeneratedKeys="true" keyProperty="id"> </insert>

版权声明
本文为[Code for wine]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225144720295d.html

Scroll to Top