Technology Sharing

[MyBatis] 40 Questions on MyBatis Theory (Part 2)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

MyBatis Theory 40 Questions》Contains the following 2 articles:


MyBatis Theory 40 Questions (Part 2)

21. How to get the generated primary key?

Added in new tags:keyProperty=“ID” That's it.

<insert id="insert" useGeneratedKeys="true" keyProperty="userId" >
	insert into user(user_name, user_password, create_time)
	values(#{userName}, #{userPassword} , #{createTime, jdbcType=TIMESTAMP})
</insert>
  • 1
  • 2
  • 3
  • 4

22. WhenEntity ClassWhat should I do if the attribute name in the table is different from the field name in the table?

(1) By querying SQL Define the alias of the field name in the statement to make the alias of the field name consistent with the attribute name of the entity class.

<select id="getOrder" parameterType="int" resultType="com.jourwon.pojo.Order">
	select order_id id, order_no orderno, order_price price form orders
	where order_id=#{id};
</select>
  • 1
  • 2
  • 3
  • 4

(2) By <resultMap> 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="com.jourwon.pojo.Order" id="orderResultMap">
	<!-- 用id属性来映射主键字段 -->
	<id property="id" column="order_id">
	<!-- 用result属性来映射非主键字段,property为实体类属性名,column为数据库表中的属性 -->
	<result property="orderno" column="order_no" />
	<result property="price" column="order_price" />
</reslutMap>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

23.What are the ways to write Mapper?

(1) Interface implementation class inheritance SqlSessionDaoSupport:Using this method, you need to write mapper interface,mapper Interface implementation class,mapper.xml document.

  • exist sqlMapConfig.xml Medium Configurationmapper.xml s position.
<mappers>
	<mapper resource="mapper.xml 文件的地址" />
	<mapper resource="mapper.xml 文件的地址" />
</mappers>
  • 1
  • 2
  • 3
  • 4
  • definition mapper interface.
  • Implementing class integration SqlSessionDaoSupportmapper Methods can be usedthis.getSqlSession() Add, delete, modify and check data.
  • spring Configuration.
<bean id=" " class="mapper 接口的实现">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
  • 1
  • 2
  • 3

(2) Use org.mybatis.spring.mapper.MapperFactoryBean

  • exist sqlMapConfig.xml Medium Configurationmapper.xml location, ifmapper.xml andmapper The interfaces have the same name and are in the same directory, so no configuration is required.
  • definition mapper interface.
<mappers>
	<mapper resource="mapper.xml 文件的地址" />
	<mapper resource="mapper.xml 文件的地址" />
</mappers>
  • 1
  • 2
  • 3
  • 4
  • mapper.xml middlenamespace formapper Address of the interface.
  • mapper The method name in the interface andmapper.xml The definition instatement ofid be consistent.
  • Spring Defined in.
<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<property name="mapperInterface" value="mapper 接口地址" />
	<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
  • 1
  • 2
  • 3
  • 4

(3) Use mapper scanner.

  • mapper.xml Document writing.
    • mapper.xml middlenamespace formapper The address of the interface;
    • mapper The method name in the interface andmapper.xml The definition instatement ofid be consistent;
    • If mapper.xml andmapper If the interface name remains the same, there is no need tosqlMapConfig.xml Configure in.
  • definition mapper Interface. Notemapper.xml The file name andmapper The interface names should be consistent and placed in the same directory.
  • Configuration mapper scanner.
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<property name="basePackage" value="mapper 接口包地址"></property>
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
  • 1
  • 2
  • 3
  • 4
  • After using the scanner spring Get from containermapper Implementation object.

24. What is MyBatis What are the interface bindings? What are the implementation methods?

Interface binding is to define any interface in MyBatis, and then bind the methods in the interface to SQL StatementsBinding, we can directly call the interface method, which is better than the original SqlSession The methods provided allow us to have more flexible choices and settings.

There are two ways to implement interface binding:

  • By annotation binding, you add @Select@Update etc. annotations, which contain SQL statements to bind;
  • pass xml Write SQL to bind, in this case, you need to specifyxml In the mapping filenamespace It must be the full path name of the interface. When the SQL statement is simple, use annotation binding. When the SQL statement is complex, usexml Binding, generally usedxml There are many bindings.

25. What are the requirements when using MyBatis's mapper interface call?

  • Mapper interface method name and mapper.xml Each sql defined inid same.
  • Mapper interface method input parameter types and mapper.xml Each sql defined inparameterType The same type.
  • Mapper interface method output parameter types and mapper.xml Each sql defined inresultType The same type.
  • Mapper.xml In the filenamespace That is the class path of the Mapper interface.

26. How does the Dao interface work? Can the methods in the Dao interface be overloaded when the parameters are different?

  • The working principle of Dao interface is JDK dynamic proxy. MyBatis will use JDK dynamic proxy to generate proxy for Dao interface when running. proxy Object, Proxy Objectproxy Will intercept the interface method and execute it insteadMappedStatement The represented SQL and then returns the SQL execution result.
  • The methods in the Dao interface cannot be overloaded because Fully qualified name + method name Preservation and retrieval strategies.

27. In the Xml mapping file of MyBatis, can the id be repeated in different Xml mapping files?

  • Different Xml mapping files, if configured namespace,So id Can be repeated; if not configurednamespace,So id Can't be repeated; after allnamespace It's not required, just best practice.
  • The reason is namespace + id As M a p < S t r i n g , M a p p e d S t a t e m e n t > Map<String, MappedStatement> Map<String,MappedStatement> Key used, if notnamespace, only id,So,id Duplication will cause data to overwrite each other.namespace,nature id You can repeat it.namespace different,namespace + id It is naturally different.

28. Briefly describe the mapping relationship between MyBatis's Xml mapping file and MyBatis's internal data structure?

MyBatis encapsulates all Xml configuration information into an All-In-One heavyweight object Configuration Internally. In the Xml mapping file,<parameterMap> The tag will be parsed asParameterMap Object, each of whose child elements will be parsed asParameterMapping object.<resultMap> The tag will be parsed asResultMap Object, each of whose child elements will be parsed asResultMapping Object. Each<select><insert><update><delete> Tags are parsed asMappedStatement Object, the SQL in the tag will be parsed asBoundSql object.

29. How does MyBatis encapsulate SQL execution results as target objects and return them? What are the mapping forms?

  • The first is to use <resultMap> Tags define the mapping relationship between column names and object attribute names one by one.
  • The second is to use the SQL column alias feature and write the column alias as the object attribute name, such as T_NAME AS NAME, object attribute names are generally name, lowercase, but column names are not case sensitive. MyBatis will ignore the case of column names and intelligently find the corresponding object attribute name. You can even write T_NAME AS NaMe, MyBatis can still work normally.

With the mapping relationship between column names and attribute names, MyBatis creates objects through reflection, and uses reflection to assign values ​​to the attributes of the object one by one and return them. Those attributes that cannot find the mapping relationship cannot be assigned.

30.In XML mapping files, besides the common select | insert | update | delete tags, what other tags are there?

There are many other tags. <resultMap><parameterMap><sql><include><selectKey>, plus dynamic SQL 9 9 9 Tags:trimwheresetforeachifchoosewhenotherwisebind Etc. Among them<sql> For SQL fragment tags,<include> Tags introduce SQL snippets,<selectKey> Generates strategy tags for primary keys that do not support auto-increment.

31. In the MyBatis mapping file, if the A tag references the content of the B tag through include, can the B tag be defined after the A tag, or must it be defined before the A tag?

Although MyBatis parses the Xml mapping file in sequence, the referenced B tag can still be defined anywhere and MyBatis can recognize it correctly.

The principle is that MyBatis parses the A tag and finds that the A tag references the B tag, but the B tag has not been parsed and does not exist yet. At this time, MyBatis will mark the A tag as unparsed, and then continue to parse the remaining tags, including the B tag. After all tags are parsed, MyBatis will re-parse those tags marked as unparsed. At this time, when parsing the A tag, the B tag already exists, and the A tag can be parsed normally.

32.Can MyBatis perform one-to-many or one-to-one relationship queries? What are the implementation methods?

Yes, not only can One-to-many, one-to-one,Well enough Many-to-many, many-to-oneThe implementation is as follows:

  • Send a separate SQL to query the related objects, assign them to the main object, and then return the main object.
  • Use nested query, similar to JOIN query, one part is the attribute value of object A, and the other part is the attribute value of related object B. The advantage is that as long as one attribute value is sent, the main object and the related object can be found.
  • Subqueries

33. Can MyBatis map Enum enumeration class?

MyBatis can map enumeration classes. In addition to enumeration classes, MyBatis can map any object to a column in a table. The mapping method is to customize a TypeHandler,accomplish TypeHandler ofsetParameter() andgetResult() Interface methods.

TypeHandler There are two functions, one is to complete thejavaType tojdbcType The second is to completejdbcType tojavaType The conversion is reflected insetParameter() andgetResult() Two methods, representing setting SQL question mark placeholder parameters and obtaining column query results.

34.What does MyBatis dynamic SQL do? What are the dynamic SQLs? Can you briefly describe the execution principle of dynamic SQL?

MyBatis dynamic SQL allows us to write dynamic SQL in the form of tags in the Xml mapping file to complete the functions of logical judgment and dynamic splicing SQL. MyBatis provides 9 9 9 Dynamic SQL tags:trimwheresetforeachifchoosewhenotherwisebind

The execution principle is to use OGNL Calculate the value of the expression from the SQL parameter object, and dynamically splice SQL according to the value of the expression to complete the function of dynamic SQL.

35.How does MyBatis perform paging? What is the principle of the paging plug-in?

MyBatis Usage RowBounds Object paging, it is forResultSet The result set performs memory paging instead of physical paging. You can directly write parameters with physical paging in SQL to complete the physical paging function, or you can use a paging plug-in to complete physical paging.

The basic principle of the paging plug-in is to use the plug-in interface provided by MyBatis to implement a custom plug-in, intercept the SQL to be executed in the plug-in's intercept method, and then rewrite the SQL according to dialect Dialect, add corresponding physical paging statements and physical paging parameters.

Example:

select * from student
  • 1

After intercepting the SQL, rewrite it to:

select t.* from (select * from student) t limit 0, 10
  • 1

36. Briefly describe the operating principle of MyBatis plug-in and how to write a plug-in?

MyBatis can only write ParameterHandlerResultSetHandlerStatementHandlerExecutor this 4 4 4 MyBatis uses JDK's dynamic proxy to generate proxy objects for the interfaces that need to be intercepted to implement the interface method interception function. 4 4 4 When a method of an interface object is used, the interception method will be entered, specificallyInvocationHandler ofinvoke() Methods, of course, will only intercept those methods that you specify to be intercepted.

Implementing MyBatis Interceptor Interface and copyintercept() method, and then write annotations for the plug-in to specify which methods of which interface to intercept. Remember, don't forget to configure the plug-in you wrote in the configuration file.

37.MyBatis's first and second level cache

  • First level cache: based on PerpetualCache The HashMap local cache has a storage scope of Session.flush orclose After that, all caches in the session will be cleared, and the first-level cache will be enabled by default.
  • The mechanism of the second-level cache is the same as that of the first-level cache, and the default is also PerpetualCache, HashMap storage, the difference is that its storage scope is MapperNamespace), and can customize the storage source, such as EhcacheThe second-level cache is not enabled by default. To enable the second-level cache, the second-level cache attribute class needs to be implemented. Serializable Serialization interface (can be used to save the state of an object), which can be configured in its mapping file<cache/>
  • For the cache data update mechanism, when a scope (first-level cache Session / second-level cache Namespace) is updated C / U / D After the operation, allselect The cache in will beclear