This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

The following is a summary of the common questions in the interview, about MyBatis part of the common problems encountered as follows:

1.Mybatis 中 $#The difference between?

$($); $($); $($);

#{} will use a placeholder for the parameter part during preprocessing. Instead, it becomes the following SQL statement:

select * from user where name = ? ;Copy the code

${} is simply a string concatenation, which is directly concatenated into the final SQL statement in the dynamic parsing phase:

select * from user where name = 'xcbeyond';
Copy the code

2. What if the name of the attribute in the entity class is different from the name of the field in the table?

The first is to make the alias of the field name consistent with the attribute name of the entity class by defining the alias of the field name in the SQL statement of the query.

<select ID = "selectOrder" parameterType = "int" resulteType = "me.gacl.domain.order" > select order_id ID, order_no orderno ,order_price price form orders where order_id=#{id}; </select>Copy the code

Second: use

to map the one-to-one correspondence between field names and entity class attribute names.

<select id="getOrder" parameterType="int" resultMap="orderresultmap"> select * from orders where order_id=#{id} </ SELECT > <resultMap type= "me.gacl.domain.order" id= "OrderResultMap" > <! > < ID property= "ID" column= "order_id" > <! -- Use the result attribute to map non-primary key fields. Property is the name of the entity class attribute. Column is an attribute in the data table -- > <result property= "orderno" column= "order_no" /> <result property= "price" column= "order_price" /> </reslutMap>Copy the code

3, How to implement a dynamic SQL in MyBatis?

Mybatis dynamic SQL can be written in Xml mapping file in the form of tag dynamic SQL, execution principle is based on the value of the expression to complete the logical judgment and dynamic splicing SQL function.

Mybatis provides nine dynamic SQL tags: trim | where | set | foreach | if | choose | s | otherwise | bind.

4. In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated?

Different Xml mapping files, if configured with namespace, then the ID can be repeated; If no namespace is configured, the ID must be unique.

Namespace + ID is used as the key of Map

. If there is no namespace, only ids are left. Duplicate ids will overwrite each other. With a namespace, the natural ID can be repeated. With different namespaces, the namespace+ ID will naturally be different.
,>