10 mybatis interview questions

JavaPub-rodert 2022-06-24 08:00:22 阅读数:231


Blogger introduction : We-Media JavaPub Independent maintainer , Fans all over the Internet 15w+,csdn Blogger 、java Quality creators in the field ,51ctoTOP10 Blogger , You know / Nuggets / Hua Wei Yun / Alibaba cloud /InfoQ And other high-quality authors 、 Focus on Java Technical fields and sidelines .

official account :JavaPub The resume template 、 Learning materials 、 The interview question bank is for you

Official account 【JavaPub】, reply : Minimum necessary interview questions , obtain 《10 swastika 301 Avenue Java Summary of classic interview questions ( Answer attached )》pdf, Easier to recite questions , One article in hand , I have

Surprise interview | Surprise interview | Surprise interview

Here are MyBatis Interview questions , I believe everyone will feel familiar and strange 、 I've seen it. I may forget it immediately after a short interview .JavaPub Sort out these easily forgotten key knowledge and answer , Recommended collection , Review and consult often .

See the comments section


This series 《 Minimum necessary interview questions 》

1. What is? MyBatis

This question is mainly about comparison JDBC Look at

  1. MyBatis It's a ORM( Object relation mapping ) frame , It encapsulates JDBC, You only need to pay attention to SQL Statement itself , It doesn't take a lot of effort to process the load driver , Create connection , establish statement And other complex processes . Developers do not need to write the original ecology sql, Can be strictly controlled sql Executive performance , High flexibility .

  2. MyBatis have access to xml Or annotations to configure mapping native information , take POJO Maps to records in the database , Almost all of them were avoided JDBC Code and manually set parameters and get the result set .

2. MyBatis The advantages of

  1. be based on SQL Statement programming , Relatively flexible ( be relative to hibernate), Support write dynamic sql Statement and can be used repeatedly .

  2. Reduce the amount of code , Eliminates redundant code .( Be similar to JDBC Encapsulation )

  3. And Spring Perfect integration .

  4. Provide mapping labels to support field relationship mapping .

3. #{} and ${} What's the difference ?

  1. #{} Precompiling 、 It's a placeholder ,${} It's string substitution 、 It's a tilde .

  2. Use #{} Can effectively prevent sql Inject , Improve the security of the system .

Mybatis Processing #{} Will be sql Medium #{} Replace with ? Number , call PreparedStatement To assign a value

/* SQL */
Such as :select * from user where name = #{userName}; set up userName=javapub
Looking at the log, we can see that the parsing will #{userName} replaced ?
select * from user where name = ?;
Then take it. javapub Put it in , Put single quotation marks outside

Mybatis Processing Of when Hou Just yes hold {} It's time to put Of when Hou Just yes hold {} Replace with the value of the variable , call Statement To assign a value

/* SQL */
Such as :select * from user where name = #{userName}; set up userName=javapub
Looking at the log, you can find that the values are spliced directly
select * from user where name = javapub;
This is very likely to happen sql Inject , Here is a simple example sql Injection cases

4. One Xml The mapping file , I can write a Dao The interface corresponds to it , This Dao How does the interface work ?

Dao Interface is what people often say Mapper Interface , The fully qualified name of the interface , It's the... In the mapping file namespace Value , The method name of the interface is in the mapping file MappedStatement Of id value , The parameters in the interface method are passed to sql Parameters of .

The methods in the interface are Cannot overload Of , the reason being that All names are limited + Method name The preservation and search strategy of .

Dao The working principle of the interface is JDK A dynamic proxy ,Mybatis Run time will Use JDK The dynamic proxy is Dao Interface generation agent proxy object , Proxy object proxy Blocking interface methods , Instead, execute the... Corresponding to the interface method MappedStatement Represented by the sql, And then sql The execution result returns .

MappedStatement:MappedStatement Maintained a <select|update|delete|insert> Encapsulation of nodes , Including the configuration of the input parameter mapping 、 Executive SQL sentence 、 Result mapping configuration and other information .

<select id="selectAuthorLinkedHashMap" resultType="java.util.LinkedHashMap">
select id, username from author where id = #{value}

5. How to get auto generated ( Lord ) Key value ?

usage :

stay <insert /> Add... To the tag useGeneratedKeys="true" Equal attribute

<insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="person" >
INSERT INTO person(name, pswd)
VALUE (#{name}, #{pswd})

When Mybatis analysis xml Node is , Read insert When configured , Will judge whether Have configuration useGeneratedKeys, If yes, it will be used Jdbc3KeyGenerator As sql The echo , Otherwise, it will take NoKeyGenerator Echo as primary key .

The bottom layer encapsulates JDBC Get auto increment primary key , That is, when you use prepareStatement perhaps Statement When , Can pass getGeneratedKeys obtain When the primary key of an insert statement is self incremented . Example

 Connection conn = DriverManager.getConnection(url, "root", "123456");
String[] columnNames = {
"id", "name"};
PreparedStatement stmt = conn.prepareStatement(sql, columnNames);
stmt.setString(1, "jack wang");
ResultSet rs = stmt.getGeneratedKeys();
int id = 0;
if (rs.next()) {

id = rs.getInt(1);
System.out.println("----------" + id);

6. Mybatis dynamic sql What's the usage? ? What's going on sql? Execution principle ?

Mybatis dynamic sql We can Xml In the mapping file , Write dynamic in the form of tags sql, Complete logical judgment and dynamic splicing sql The function of .

Mybatis Provides 9 Species dynamics sql label : trim | where | set | foreach | if | choose | when | otherwise | bind.

Its executive principle is , Use OGNL from sql Evaluate the value of the expression in the parameter object , Dynamically concatenate according to the value of the expression sql, To complete the dynamic sql The function of .

Is it a little confused , Read on :

The popular science :

OGNL yes Object-Graph Navigation Language Abbreviation , object - Graph line navigation language . for example #{} grammar .

OGNL The function is to do data interaction between objects and views , You can access the object's properties and call the object's methods , The structure diagram of the whole object can be iterated through the expression .

Refer to a very vivid example .

There is a student object student, The attributes are id = 10,name = ‘ Xiao Ming ’ and Course objects course, among course There are properties in the object : fraction score = 88, ranking rank = 5.

The object relationship diagram is as follows :

name: Xiao Ming

When context ( Environmental Science ) The object in is student When , That is to say Mybatis The parameter object passed in during query in is student When :

adopt OGNL Expression gets the property value of the object in the context directly , such as :

#{id} —> 10, Relative to the current context object .getId(), namely student.getId() .

#{name} —> Xiao Ming .

#{course.score} —> 88, amount to student.getCourse().getScore().

therefore , adopt OGNL expression , The structure diagram of the whole object can be iterated .

Release 《 Minimum necessary interview questions 》

7. What is? Mybatis The first level of 、 Second level cache ?

First level cache : be based on PerpetualCache Of HashMap Local cache , Its storage scope is Session, When Session flush or close after , The Session All in Cache Will be emptied , The default L1 cache is on .

When Mybaits And Spring When integrating , No Spring Within the method of the transaction , Every time a database is requested , Will create a new SqlSession, At this time, the L1 cache is not used . Except for business problems , And I called Sqlsession Modification of 、 add to 、 Delete 、commit()、close() Other methods , The L1 cache will also be emptied .

Second level cache It has the same mechanism as the first level cache , Default is also used PerpetualCache,HashMap Storage , The difference is that the storage scope is Mapper(Namespace). Even if the second level cache is turned on , Different sqlsession The cache data between users can't be accessed if they want to , We have to wait until sqlsession After it's closed , The data in the first level cache will be written to the second level cache . The second level cache is not turned on by default .

Most applications now support distributed , Generally, middleware is used as the cache layer , such as redis. Turn on MyBatis The L2 cache of will also be serialized and deserialized one more step , Impact on service performance .

8. MyBatis How it works

A picture is worth a thousand words

 Insert picture description here

  1. Read MyBatis The configuration file :mybatis-config.xml by MyBatis Global configuration file for , Configured with MyBatis Operation environment and other information , For example, database connection information .

  2. Load mapping file . The mapping file is SQL The mapping file , This file is configured to operate the database SQL sentence , Need to be in MyBatis The configuration file mybatis-config.xml Load in .mybatis-config.xml File can load multiple mapping files , Each file corresponds to a table in the database .

  3. Construct a conversation factory : adopt MyBatis Build session factory with configuration information such as environment SqlSessionFactory.

  4. Create session object : Created by session factory SqlSession object , This object contains the execution SQL All methods of statement .

  5. Executor actuator :MyBatis The bottom defines a Executor Interface to operate the database , It will be based on SqlSession The passed parameters dynamically generate what needs to be executed SQL sentence , Also responsible for query cache maintenance .

  6. MappedStatement object : stay Executor There is one of the execution methods of the interface MappedStatement Parameters of type , This parameter encapsulates the mapping information , Used to store the SQL Of the statement id、 Parameter information .

  7. Input parameter mapping : The input parameter type can be Map、List And so on , It can also be basic data types and POJO type . The input parameter mapping process is similar to JDBC Yes preparedStatement The process of setting parameters for objects .

  8. Output result mapping : The output result type can be Map、 List And so on , It can also be basic data types and POJO type . The output mapping process is similar to JDBC The process of parsing the result set .

9. What is? MyBatis Interface binding of ? What are the ways to do it ?

Interface binding , Is in the MyBatis Any interface defined in , Then the method in the interface and SQL Statement binding , We can call the interface method directly , It's much better than before SqlSession We can have more flexible choices and settings .

Interface binding can be implemented in two ways :

  • adopt Annotation binding , It is to add... To the interface method @Select、@Update Etc , It contains Sql Statement to bind ;

  • adopt xml It says in it SQL To bind , under these circumstances , To specify xml In the mapping file namespace Must be the full pathname of the interface . When Sql When the sentences are simple , Bind... With annotations , When SQL When the sentences are complicated , use xml binding , It's usually used xml There are a lot of binding .

10. Mybatis Paging principle of

Mybatis Use RowBounds Object to paginate , It's about ResultSet Memory paging performed by result set , Not physical paging , Therefore, it is generally not used . Can be in sql Write parameters with physical paging directly to complete the physical paging function , You can also use paging plug-ins to do physical paging .

The principle of the paging plug-in is to use MyBatis Provided plug-in interface , Implement custom plug-ins , In the plug-in's interception method , Intercept what is to be executed SQL, And then according to the settings dialect( dialect ), And set paging parameters , rewrite SQL , Generate... With paging statements SQL, Execute the rewritten SQL, This enables paging .

give an example :select * from student, Intercept sql Then rewrite it to :select t.* from (select * from student)t limit 0,10.

 Insert picture description here

Low valley energy storage

《 Minimum necessary interview questions 》

10 No way Java Basic interview questions

10 No way MySQL Basic interview questions

10 No way Java Concurrent basic interview questions

10 No way JVM Interview questions

10 No way ElasticSearch Interview questions

10 No way Spring Interview questions

10 No way Redis Interview questions

10 No way Kafka Interview questions

10 No way MyBatis Interview questions

10 No way Docker Interview questions

Official account , reply 1024, obtain Java Learning route mind map 、 Join the source code program learning exchange group
copyright:author[JavaPub-rodert],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240421248545.html