Mybatis is a great persistence framework!


ssm framework: the configuration file. Best way: Look at official documents

1. Introduction

1.1, What is Mybatis

  • MyBatis is an excellent persistence framework.
  • It supports customizing SQL, stored procedures, and advanced mappings.
  • MyBatis avoids almost all JDBC code and setting parameters manually and getting result sets.
  • MyBatis can use simple XML or annotations to configure and map native types, interfaces, and JavaPOJOs (Plain Old JavaObjects, plain old Java objects) as records in the database.
  • MyBatis was originally an open source project for apache, iBatis, which was migrated to google code by apache software foundation in 2010 and renamed E to MyBatis.
  • Migrated to Github in November 2013.

How do I get MyBatis?

1.2. Persistence

Data persistence.

  • Persistence is the process of transforming program data into persistent and transient states
  • Memory: Lose when power is off.
  • Database (Jdbc), io file persistence.
  • Life: Refrigerated, canned.

Why do you need persistence?

  • There are some objects that can't be thrown away.
  • Memory is too expensive

1.3, Persistence Layer

Dao Layer, Service Layer, Controller Layer...

  • Code block to complete persistence work.
  • Layer boundaries are obvious.

1.4 Why Mybatis is needed

  • Help program apes store data in databases.
  • Convenient.
  • Traditional JDBC code is too complex. Simplify. Frame. Automation.
  • You can do it without Mybatis. It's easier to get started. There is no difference in technology
  • Somewhat:
    o Simple and easy to learn
    o Flexibility
    Separation of o sql and code improves maintainability.
    o Provides mapping labels to support object-database orm field relationship mapping
    o Provides object-relational mapping labels to support maintenance of object-relational organization
    o Provides xml tags to support writing dynamic sql.

Most importantly, there are many people learning to use

2. First Mybatis program

Idea: Build Environment -- "Import Mybatis --> Write Code --" Test!

2.1. Setting up environment

Set up database

USE 'mybatis;
INSERT INTO user (id), name, pwd) VALUES(1,'Wang Wu,'123456'), (2.'Zhang San','123456', (3,'Li Si','123890')

New Project
1. Create a new maven project
2. Delete src directory
3. Import maven dependencies


2.2. Create a module

  • Write the core configuration file for mybatis

    <environments default="development">
        <!-- Environment variables: Multiple environment variables can be configured, such as when using multiple data sources. -->
        <environment id="development">
            <!-- Transaction Manager -->
            <transactionManager type="JDBC"/>
            <!-- data source -->
            <dataSource type="">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="111111"/>
  • Writing mybatis tool class

    package com.syj.utils;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;


    public class MyBatisUtils {

    private static  SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();


2.3. Writing Code

  • Entity Class

    package com.syj.entily;

    import lombok.*;

    public class User {
    private int id;
    private String name;
    private String pwd;


  • Dao interface

    package com.syj.dao;

    import com.syj.entily.User;

    import java.util.List;

    public interface UserDao {
    List getUserList();

  • Interface implementation class converted from UserDaoImpl to a Mapper configuration file

    <?xml version="1.0" encoding="UTF-8" ?> select * from user

2.4. Testing

junit test

Problems encountered
1. Profile not registered
2. Binding interface error
3. Method name is incorrect
4. Incorrect return type
5.Maven Export Resource Issue


1, namespace

The package name in the namespace should match the package name of the Dao/Mapper interface!

2, select

Select, query statement;

  • .id: is the method name in the corresponding namespace;
  • .resultType: Return value of Sql statement execution!.
  • parameterType: Parameter type!

1. Write interfaces

//Query Users Based on Id
User getUser(User user)

2. Write Sql statements in the corresponding Mapper

<select id="getuserById" parameterType="int" resultType="com. kuang. pojo.user">
	select * from mybatis.user where id = #{id}

3. Testing

public void getuserById( 
Sqlsession sqlsession = Mybatisutils.getsqlsession ();
usermapper mapper = sqlSession. getMapper (userMapper.class);
User user = mapper. getuserById (1);
system.out.println (user);




Be careful:

  • Additions and deletions require transaction submission!

6. Analysis Errors

  • .Labels do not match the wrong resource mapper, you need to use a path!
  • The program configuration file must conform to the specifications!
  • NullPointerException, not registered with resource!
  • Output xml file has Chinese scrambling problem!.
  • There are no export problems for maven resources!

7. Universal Map

8. Think Questions

How to write a fuzzy query?

4. Configuration resolution

1. Core Profile

2. Environment Configuration

3. Properties

4. Type alias typeAilases

5. Settings

6. Other Configurations

7. Mappers

8. Life Cycle and Scope

Each of these mapper s represents a specific business!

5. Resolve the inconsistency between attribute name and field name

5.1. Questions


6. Log

6.1. Log Factory


1. Importing packages from log4j


### Set up###
log4j.rootLogger = debug,stdout,D,E

### Output information to control lift ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = DEBUG org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### output DEBUG Logs above level to=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### output ERROR Logs above level to=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

7. Paging

7.2, RowBounds Paging

Paging is no longer implemented using SQL

7.3, Paging Plugin

8. Develop using annotations

81. Interface-oriented programming

Mybatis Detailed Execution Process



Project Lombok is a Java library that automatically inserts your editors and build tools to add interest to your java. Never write another getter or equals method again, your class has a fully functional builder with only one comment. Automation log variables, and so on.

Use steps
1. Install Lombok plug-in in idea
2. Import Lombokjar packages into your project


3. Annotate the entity class

@NoArgsConstructor/@RequiredArgsConstructor /@AllArgsConstructor

@Data:Parametric construction, get, set, tostring, hashcode, equals
@Getter  @Setter

10. Many-to-one processing (associated queries)


  • Multiple students, one teacher
  • On the student side, associate...multiple students, associate a teacher [many-to-one]
  • For teachers, set, a teacher, there are many students [one-to-many]

Test environment setup

1. Import Lombok
2. New Entity Class Teacher,Studnet
3. Establish mapper interface
4. Create mapper.xml file
5. Register our Mapper interfaces or files in Core Matches [in whatever way you like]
6. Test whether the query succeeded

Nested processing by query (subquery)

Entity Class

public class Teacher{
	private int id;
	privite String name;

public class Student{
	private int id;
	privite String name;
	//Students need to associate a teacher
	privite Teacher teacher;

Nested Processing by Results (Joint Table Query)

Review Mysql many-to-one query

  • Subquery
  • Joint Table Query

11. One-to-many processing

For example: a teacher has many students
For teachers, it's one-to-many
Entity Class

public class Student{
	private int id;
	privite String name;
	private int tid;

public class Teacher{
	private int id;
	privite String name;
	//A teacher has more than one student
	privite List<Student> Students

Nested Processing by Result

Nested Processing by Query


1. association: association many-to-one
2. Collection: collection one-to-many
3.javaType & ofType

  1. JavaType is used to specify the type of attribute in an entity class
  2. ofType is used to specify the pojo type mapped to a List or collection, the constraint type in a generic!

Points of Attention
Ensure the readability of SQL and make it as easy to understand as possible
.Note the one-to-many and many-to-one problems with attribute names and fields!
If the problem is not good enough to troubleshoot the errors, you can use the log, we recommend using Log4j

Interview frequency is high.
Mysql Engine
.InnoDB underlying principles
.Index optimization!

12. Dynamic SQL

What is dynamic SQL: Dynamic SQL is the generation of different SQL statements based on different conditions
Dynamic SQL is a feature that allows you to get rid of this pain entirely.

Set up environment





The so-called dynamic SQL is essentially a SQL statement, but we can execute a logical code at the SQL level
where, set, choose , when


SQL Fragment

Sometimes, we may extract parts of some functions for easy reuse!
1. Use SQL tags to extract common parts

2. Use Include tag references where necessary

Matters needing attention:

  • .Better to define SQL fragments based on a form!
  • Do not have where Tags

    Dynamic SQL is just splicing SQL statements. We just need to ensure the correctness of SQL and arrange and combine them according to the format of SQL.
    Now write out the complete SQL in Mysql and modify it accordingly to make our dynamic SQL implementation universal.

13. Caching

13.1. Introduction

1. What is Cache
Temporary data in memory exists.
By putting the data that users often query in the cache (memory), users can query the data from the cache instead of from the disk (relational database data files), which improves the query efficiency and solves the performance problem of high concurrent systems.

2. Why use caching
Reduce the number of interactions with the database, reduce system overhead, and improve system efficiency.

3. What kind of data can use caching
Data that is queried frequently and changes infrequently.

13.2, Mybatis Cache

  • MyBatis includes a very powerful query cache feature that makes it very easy to customize and configure the cache. Caching can greatly improve query efficiency.
  • By default, two levels of caching are defined in the MyBatis system: first-level caching and second-level caching.
    o By default, only one level of cache is turned on. (SqlSession level cache, also known as local cache).
    o Secondary cache needs to be opened and configured manually, it is based on namespace level.
    o To improve scalability, MyBatis defines the cache interface Cache. We can customize the secondary cache by implementing the Cache interface

13.3, Level 1 Cache

  • A first-level cache is also called a local cache:.
    o Data queried during the same session with the database will be placed in the local cache.
    o If you need to get the same data later, take it directly from the cache, and you don't have to query the database anymore. Bold Style

Test steps:
1. Open the log!
2. Test querying the same record twice in a Sesion
3. View log output

Cache failure:
1. Query different things
2. Add or delete operations, may change the original data, so the cache must be refreshed!

3. Query different Mapper.xml
4. Clean up the cache manually!


  • The first level cache is turned on by default and only works in one SqlSession, that is, to get the segment connected to a closed connection!
  • A first-level cache is a Map.

13.4, Level 2 Cache

  • Second-level caches are also called global caches. Because the scope of first-level caches is too low, second-level caches are born.
  • A namespace-level cache, a namespace, corresponding to a secondary cache;
  • Working mechanism.
    o A session queries a piece of data, which is placed in the first level cache of the current session;.
    o If the current session is closed, the corresponding first-level cache for this session will be gone; But all we want is that the session is closed and the data in the first level cache is saved in the second level cache.
    o New session query information, you can get content from the secondary cache;
    o Data found by different mapper s will be placed in their own cache (map);


  • As long as the secondary cache is turned on, it will be valid under the same Mapper.
  • All data is first placed in the first level cache;
  • Only when the session is committed or closed will it be committed to the secondary buffer!

Caching principles

13.6, Custom Cache ehcache

To use ehcache in your program, first guide the package!



Insert a code snippet here

Redis database to cache! K-V

Tags: Back-end Front-end Android Interview

Posted by greencoin on Sun, 14 Aug 2022 02:44:53 +0930