编程知识 cdmana.com

25 mybatis interview questions, you are worth having~

1.JDBC There are several steps ?

JDBC It can be roughly divided into six steps :

  1. Load driver
  2. Get database connection
  3. Create a Statement object
  4. Operating the database , We will increase, delete, and change inspections
  5. Get the result set
  6. close resource

2. What is? Mybatis?

If you are asked during an interview , Just name the following three :

*

MyBatis Is an excellent persistence layer framework , It supports customization SQL、 Stored procedures and high-level mappings .

MyBatis It dispenses with almost everything JDBC Code and the work of setting parameters and getting result sets .

MyBatis It can be done by simple XML Or annotations to configure and map primitive types 、 Interface and Java POJO(Plain Old Java Objects, Ordinary old-fashioned Java object ) For records in the database .

*

—— From official website . I recommend that you answer according to the official .

3. What is? ORM?

Its full name is Object Relational Mapping. object - mapping - Relational database . Object relation mapping ( abbreviation ORM, or O/RM, or O/R mapping), It is used to realize the conversion of data between different types of systems in object-oriented programming language . To put it simply ,ORM By using metadata that describes the mapping between objects and databases , Mapping objects in a program to a relational database .

ORM Provides another pattern for implementing the persistence layer , It uses mapping metadata to describe the mapping of object relationships , bring ORM Middleware can act as a bridge between business logic layer and database layer of any application .

4. say something ORM Advantages and disadvantages

「 advantage 」1. Improved development efficiency . because ORM It can be done automatically Entity Object and database Table Mapping fields and attributes , So we may not actually need a dedicated 、 Massive data access layer .2.ORM Provides mapping to the database , no need sql Direct code , Be able to get data from a database just like an object .

「 shortcoming 」 At the expense of program execution efficiency and fixed mode of thinking , Reduced development flexibility .

In terms of system structure , use ORM The system is generally a multi-layer system , There are more layers in the system , Efficiency will be reduced .ORM It's a completely object-oriented approach , And the object-oriented approach will also have a certain impact on performance .

When we develop the system , Generally, there are performance problems . Performance problems are mainly caused by incorrect algorithm and incorrect use of database .

ORM The generated code is generally unlikely to write efficient algorithms , It is more likely to be misused in database applications , It is mainly reflected in the extraction of persistent objects and data processing , If it's used ORM, The programmer is likely to extract all the data into memory objects , And then it's filtered and processed , This can lead to performance problems .

When you persist objects ,ORM Generally, all properties are persisted , Sometimes , This is not to be hoped for . but ORM It's a tool , Tools do solve some duplication , Simple labor . This is undeniable . But we can't expect tools to solve all problems once and for all , Some problems need to be dealt with specially , But the parts that need special treatment for most systems , There should be very few .

5. say something Mybaits Advantages and disadvantages

advantage

① be based on SQL Statement programming , Fairly flexible , No impact on the existing design of the application or database ,SQL Written in XML in , relieve sql Coupling with program code , Convenient for unified management ; Provide XML label , Support writing dynamics SQL sentence , And reusable .

② And JDBC comparison , Less 50% Code quantity above , Eliminated JDBC A lot of redundant code , No need for manual switch connection ;

③ Good compatibility with various databases ( because MyBatis Use JDBC To connect to the database , So as long as JDBC Supported databases MyBatis All support ).

④ Can and Spring Good integration ;

⑤ Provide mapping label , Support object and database ORM Field relation mapping ; Provide object relation mapping labels , Support object relationship component maintenance .

shortcoming

① SQL Statement writing is heavy , Especially when there are many fields 、 Association table multi time , Write to developers SQL There are certain requirements for the power of sentences .

② SQL Statement depends on Database , Poor database portability , Can't change database at will .

MyBatis The frame is suitable for :

(1)MyBatis Focus on SQL In itself , Is a flexible enough DAO Layer solution .

(2) The demand for performance is very high , Or projects with more changes in demand , Like the Internet Project ,MyBatis It would be a good choice .

6.Mybatis How is paging done ?

Mybatis Use RowBounds Object to paginate , It's about ResultSet Memory paging performed by result set , Not physical paging , Look up the data first , And then pagination .

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 .

7. What's the basic principle of paging plug-ins ?

The basic principle of paging plug-ins is to use Mybatis Provided plug-in interface , Implement custom plug-ins , In the plug-in's interception method, intercept the execution to be performed sql, Then rewrite sql(SQL Splicing limit), according to dialect dialect , Add the corresponding physical page statement and physical page parameters , Technology is used JDK A dynamic proxy , Using the chain of responsibility design pattern .

8. sketch Mybatis How the plug-in works ?

Mybatis You can only write for ParameterHandler、ResultSetHandler、StatementHandler、Executor this 4 Plug ins for various interfaces ,Mybatis Use JDK Dynamic proxy for , Generate a proxy object for the interface to be intercepted to implement the interface method interception function , Whenever this is performed 4 Methods of interface objects , It's going to enter the intercept method , The concrete is InvocationHandler Of invoke() Method , Of course , It will only intercept those methods that you specify to intercept .

9. How to write a plug-in ?

Writing a plug-in : Realization Mybatis Of Interceptor Interface and copy intercept() Method , Then annotate the plug-in , Specify which methods of which interface to intercept , Finally, configure the plug-in you write in the configuration file . recommend : Recommended collection ,mybatis Detailed explanation of plug-in principle

10.Mybatis dynamic sql What's the usage? ?

Mybatis dynamic sql Can be in Xml In the mapping file , Write dynamic in the form of tags sql, The execution principle is to complete logical judgment according to the value of expression And dynamically adjust sql The function of .

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

11.Xml What labels are in the mapping file ?

In addition to the usual select|insert|updae|delete Beyond labels , also :

<resultMap><parameterMap><sql><include><selectKey>, Plus the dynamic sql Of 9 A label , among <sql> by sql Fragment tags , adopt <include> Tags introduced sql fragment ,<selectKey> Generate policy tags for primary keys that do not support auto increment .

12.Mybatis Whether delay loading is supported ?

Mybatis Support only association Associate objects with collection Delay loading of associated collection objects ,association It means one-on-one ,collection It means one to many query . stay Mybatis In profile , You can configure whether to enable lazy loading lazyLoadingEnabled=true|false.

13. What's the basic principle of delayed loading ?

The basic principle of delayed loading is , Use CGLIB Create a proxy object for the target object , When the target method is called , Enter the interceptor method .

For example, call a.getB().getName(), Interceptor invoke() Methods found a.getB() yes null value , Then the saved query Association will be sent separately B Object's sql, hold B Look up , And then call a.setB(b), therefore a The object of b The property has a value , Then finish a.getB().getName() Method call .

Yes, of course , Not only is it Mybatis, Almost everything includes Hibernate, The principle of supporting delayed loading is the same .

14.mapper.xml File corresponding Dao The interface principle is ?

In short : Used JDK Dynamic proxy and reflection , Connect the interface with xml It's all tied together .

15.Dao Methods in the interface , Can parameters be overloaded when they are different ?

Cannot overload .

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

${} It's string substitution ,#{} Is the preprocessing ;

Mybatis When dealing with , Is to put {} Directly replace with the value of the variable . and Mybatis Processing #{} when , Would be right sql Statement to preprocess , take sql Medium #{} Replace with ? Number , call PreparedStatement Of set Method to assign a value ;

Use #{} Can effectively prevent SQL Inject , Improve system security .

17.Mybatis Perform bulk insert , Can I return the database primary key list ?

1、 For databases that support the generation of auto increment primary keys : increase useGenerateKeys and keyProperty ,<insert> Tag attributes .

2、 Database that does not support generating auto increment primary keys : Use <selectKey>.

The way :

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreach item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </foreach>
</insert>

Be careful Mybatis Version of , The official is here 3.3.1 Batch addition of return primary keys has been added to the version id The function of .

18. Different Xml The mapping file ,id Is it possible to repeat ?

Different Xml The mapping file , If the namespace, that id Can be repeated ; If not configured namespace, that id Can't repeat ; After all namespace It's not necessary , It's just best practice .

The reason is that namespace+id As a Map<String, MappedStatement> Of key The use of , without namespace, That's all id, that ,id Repetition can cause data to overlap with each other . With namespace, natural id You can repeat ,namespace Different ,namespace+id Naturally, it's different .

19.Mybatis in Executor The difference between actuators is ?

Mybatis There are three basic Executor actuator ,「SimpleExecutor、ReuseExecutor、BatchExecutor.」

 

 

SimpleExecutor: Every time update or select, Just turn on one Statement object , Shut down immediately after use Statement object .

ReuseExecutor: perform update or select, With sql As key lookup Statement object , Use when you exist , Create... If it doesn't exist , After use , Don't shut down Statement object , It's placed in Map<String, Statement> Inside , For the next use . in short , It's reuse Statement object .

BatchExecutor: perform update( No, select,JDBC Batch processing does not support select), Will all sql All added to the batch (addBatch()), Waiting for unified execution (executeBatch()), It caches multiple Statement object , Every Statement Objects are addBatch() After the completion of , Wait for one by one executeBatch() The batch . And JDBC Batch processing is the same .

Scope of action :Executor These characteristics of , They are strictly limited to SqlSession Within the life cycle .

20. Why do you say Mybatis It's semi-automatic ORM Mapping tools ?

Hibernate It's fully automatic ORM Mapping tools , Use Hibernate When querying associated objects or associated collection objects , It can be obtained directly from the object relation model , So it's fully automatic .

and Mybatis When querying associated objects or associated collection objects , It needs to be written manually sql To complete , therefore , It's called semi-automatic ORM Mapping tools .

(2)Mybatis Write the original ecology directly sql, Can be strictly controlled sql Executive performance , High flexibility , It is very suitable for software development with low requirements for relational data model , Because the requirements of this kind of software change frequently , Once the demand changes, the output must be fast . But the premise of flexibility is this mybatis Database neutrality cannot be achieved , If you need to implement software that supports multiple databases , You need to customize multiple sql The mapping file , Big workload .

(3)Hibernate object / Strong relational mapping capability , Good database independence , Software with high requirements for relational models , If you use hibernate Development can save a lot of code , Increase of efficiency .

Actually, about common ORM The frame also has Spring Of JPA, Later interviews may be more inclined to ask JPA and Mybatis The difference between the . I hope you will pay attention to .

21.Mybatis What labels are in the global profile ?

*

configuration To configure

properties attribute : Can be loaded

properties Profile information

settings Set up : You can set mybatis The global properties of

typeAliases Type name

typeHandlers Type processor

objectFactory Object factory

plugins plug-in unit

environments Environmental Science

environment environment variable

transactionManager Transaction manager

dataSource data source

mappers mapper

*

22. What to do when the attribute name in the entity class is different from the field name in the table ?

The first 1 Kind of : Through the query of sql The alias of the field name defined in the statement , Make the alias of the field name consistent with the property name of the entity class .

<select id="selectById" resultMap="User">
        select id, name as userName, pwd as password from m_user
        <where>
            <if test="id != null">
                id = #{id}
            </if>
        </where>
    </select>

The first 2 Kind of : adopt <resultMap> To map the one-to-one correspondence between field names and entity class property names .

The first 3 Kind of : When using annotations , Use Result, It's similar to the second one .

23. Fuzzy query like How to write a sentence ?

The first 1 Kind of : stay Java Add in code sql wildcard .

String wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like #{value}
</select>

The first 2 Kind of : stay sql Concatenate wildcards in statements , Can cause sql Inject

String wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like "%"#{value}"%"
</select>

24.Mybatis Build steps ?

The whole process :

 

 

25. Briefly Mybatis Manual programming steps for ?

  1. establish SqlSessionFactory

  2. adopt SqlSessionFactory establish SqlSession

  3. adopt sqlsession Perform database operations

  4. call session.commit() Commit transaction

  5. call session.close() Close session

25.Mybatis The flow of work is ?

Mybatis The workflow can be roughly divided into four steps :

 

版权声明
本文为[Tian Weichang]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225131451433j.html

Scroll to Top