2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
《MyBatis Theory 40 Questions》Contains the following 2 articles:
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) 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>
(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) Interface implementation class inheritance SqlSessionDaoSupport
:Using this method, you need to write mapper
interface,mapper
Interface implementation class,mapper.xml
document.
sqlMapConfig.xml
Medium Configurationmapper.xml
s position.<mappers>
<mapper resource="mapper.xml 文件的地址" />
<mapper resource="mapper.xml 文件的地址" />
</mappers>
mapper
interface.SqlSessionDaoSupport
。mapper
Methods can be usedthis.getSqlSession()
Add, delete, modify and check data.spring
Configuration.<bean id=" " class="mapper 接口的实现">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
(2) Use org.mybatis.spring.mapper.MapperFactoryBean
。
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.mapper
interface.<mappers>
<mapper resource="mapper.xml 文件的地址" />
<mapper resource="mapper.xml 文件的地址" />
</mappers>
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>
(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;mapper.xml
andmapper
If the interface name remains the same, there is no need tosqlMapConfig.xml
Configure in.mapper
Interface. Notemapper.xml
The file name andmapper
The interface names should be consistent and placed in the same directory.mapper
scanner.<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper 接口包地址"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
spring
Get from containermapper
Implementation object.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:
@Select
、@Update
etc. annotations, which contain SQL statements to bind;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.mapper.xml
Each sql defined inid
same.mapper.xml
Each sql defined inparameterType
The same type.mapper.xml
Each sql defined inresultType
The same type.Mapper.xml
In the filenamespace
That is the class path of the Mapper interface.proxy
Object, Proxy Objectproxy
Will intercept the interface method and execute it insteadMappedStatement
The represented SQL and then returns the SQL execution result.namespace
,So id
Can be repeated; if not configurednamespace
,So id
Can't be repeated; after allnamespace
It's not required, just best practice.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.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.
<resultMap>
Tags define the mapping relationship between column names and object attribute names one by one.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.
There are many other tags. <resultMap>
、<parameterMap>
、<sql>
、<include>
、<selectKey>
, plus dynamic SQL
9
9
9 Tags:trim
、where
、set
、foreach
、if
、choose
、when
、otherwise
、bind
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.
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.
Yes, not only can One-to-many, one-to-one,Well enough Many-to-many, many-to-oneThe implementation is as follows:
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.
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:trim
、where
、set
、foreach
、if
、choose
、when
、otherwise
、bind
。
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.
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
After intercepting the SQL, rewrite it to:
select t.* from (select * from student) t limit 0, 10
MyBatis can only write ParameterHandler
、ResultSetHandler
、StatementHandler
、Executor
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.
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.PerpetualCache
, HashMap storage, the difference is that its storage scope is Mapper
(Namespace
), and can customize the storage source, such as Ehcache
The 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/>
。C
/ U
/ D
After the operation, allselect
The cache in will beclear
。