Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java MyBatis Framework

Java MyBatis Framework

Common Java Libraries Common Java Libraries


MyBatis is an excellent persistence framework that simplifies the interaction between Java applications and relational databases. MyBatis maps SQL statements to Java objects through XML or annotations, avoiding the large amount of boilerplate code in traditional JDBC programming.


Core features of MyBatis

1. SQL and code separation

MyBatis allows developers to separate SQL statements from Java code, storing them in XML files or annotations, making the code clearer and easier to maintain.

2. Automatic mapping

MyBatis can automatically map database query results to Java objects, greatly reducing the workload of data conversion.

3. Dynamic SQL

MyBatis provides powerful dynamic SQL capabilities, which can generate different SQL statements based on different conditions.

4. Caching mechanism

MyBatis has a built-in first-level cache and second-level cache, which can effectively improve application performance.


Basic architecture of MyBatis

1. Core components

2. Workflow

  1. The application creates SqlSessionFactory through SqlSessionFactoryBuilder
  2. SqlSessionFactory creates SqlSession
  3. SqlSession obtains an instance of the Mapper interface
  4. Call the Mapper method to perform database operations
  5. Commit the transaction and close SqlSession

MyBatis configuration

1. Main configuration file (mybatis-config.xml)

Example

   

       

           

           

               

               

               

               

           

       

   

   

       

   

2. Mapper file example

Example

   

   

   

        INSERT INTO users(name, email) VALUES(#{name}, #{email})

   


Basic usage of MyBatis

1. Obtain SqlSession

Example

String

resource

=

"mybatis-config.xml"

;

InputStream

inputStream

=

Resources.

getResourceAsStream

(

resource

)

;

SqlSessionFactory sqlSessionFactory

=

new

SqlSessionFactoryBuilder

(

)

.

build

(

inputStream

)

;

SqlSession session

=

sqlSessionFactory.

openSession

(

)

;

2. Execute query

Example

// Method 1: Use SqlSession directly

User user

=

session.

selectOne

(

"com.example.mapper.UserMapper.getUserById"

,

1

)

;

// Method 2: Through the Mapper interface

UserMapper mapper

=

session.

getMapper

(

UserMapper.

class

)

;

User user

=

mapper.

getUserById

(

1

)

;

3. Execute insert

Example

User newUser

=

new

User

(

)

;

newUser.

setName

(

"Zhang San"

)

;

newUser.

setEmail

(

"zhangsan@example.com"

)

;

int

rows

=

mapper.

insertUser

(

newUser

)

;

session.

commit

(

)

;

// Commit the transaction


MyBatis dynamic SQL

MyBatis provides various dynamic SQL elements that can dynamically generate SQL statements based on different conditions:

1. if element

Example

2. choose/when/otherwise element

Example

3. foreach element

Example


MyBatis association queries

1. One-to-one association

Example

   

   

   

       

       

       

   

2. One-to-many association

Example

   

   

   

       

       

       

   


MyBatis caching mechanism

1. First-level cache

The first-level cache is a SqlSession-level cache, enabled by default. Within the same SqlSession, the same query executes the SQL only once.

Characteristics:

-

Executing INSERT/UPDATE/DELETE Operation

-

called sqlSession.clearCache()

-

Executing a transaction rollback

-

Configuring a different Statement ID(even if the SQL is the same)

Notes:

Example

// Example: the same query is executed only once in the same SqlSession

User user1

=

sqlSession.

selectOne

(

"getUserById"

,

1

)

;

 

// Execute SQL

User user2

=

sqlSession.

selectOne

(

"getUserById"

,

1

)

;

 

// Retrieve from cache

2. Second-level cache

The second-level cache is a Mapper-level cache that can be shared by multiple SqlSessions. It needs to be enabled in the configuration file:


      

And configured in the Mapper file:



  flushInterval="60000"         
  size="512"                    
  readOnly="true"/>             

Cache strategy comparison:

Strategy Description Applicable scenarios
LRU Least Recently Used General use
FIFO First In First Out Fixed-order access
SOFT Soft reference Memory-sensitive scenarios
WEAK Weak reference Extremely memory-sensitive

MyBatis integration with Spring

1. Dependency configuration (recommended for modern Spring Boot)

Example

   

   

       

org.mybatis.spring.boot

       

mybatis-spring-boot-starter

       

3.0.3

   

   

   

       

org.mybatis

       

mybatis-spring

       

3.0.3

   

   

   

   

       

com.mysql

       

mysql-connector-j

       

8.0.33

   

2. Configuration approaches (three mainstream methods)

Option 1: Spring Boot auto-configuration (simplest)

Example

application.yml

mybatis

:

  mapper-locations

:

classpath*:mapper/**/*.xml

  type-aliases-package

:

com.example.model

  configuration

:

    map-underscore-to-camel-case

:

true  

Automatic camel-case conversion

Option 2: Full Java Config configuration (fine-grained control)

Example

@Configuration

public

class

MyBatisConfig

{

   

    @Bean

    @ConfigurationProperties

(

prefix

=

"spring.datasource"

)

   

public

DataSource dataSource

(

)

{

       

return

DataSourceBuilder.

create

(

)

.

build

(

)

;

   

}

    @Bean

   

public

SqlSessionFactory sqlSessionFactory

(

DataSource dataSource

)

throws

Exception

{

        SqlSessionFactoryBean factory

=

new

SqlSessionFactoryBean

(

)

;

        factory.

setDataSource

(

dataSource

)

;

        factory.

setTypeAliasesPackage

(

"com.example.model"

)

;

       

       

// Custom configuration (example)

        org.

apache

.

ibatis

.

session

.

Configuration

config

=

new

Configuration

(

)

;

        config.

setMapUnderscoreToCamelCase

(

true

)

;

        config.

setDefaultFetchSize

(

100

)

;

        factory.

setConfiguration

(

config

)

;

       

       

// Plugin configuration (example)

        factory.

setPlugins

(

           

new

MyBatisInterceptor

(

)

,

           

new

PaginationInterceptor

(

)

       

)

;

       

       

return

factory.

getObject

(

)

;

   

}

    @Bean

   

public

MapperScannerConfigurer mapperScanner

(

)

{

        MapperScannerConfigurer scanner

=

new

MapperScannerConfigurer

(

)

;

        scanner.

setBasePackage

(

"com.example.mapper"

)

;

        scanner.

setAnnotationClass

(

Repository

.

class

)

;

// Restrict annotation scanning

       

return

scanner

;

   

}

}

Option 3: Traditional XML configuration (compatible with legacy projects)

Example

   

   

   

3. Transaction management configuration

Example

@Configuration

@EnableTransactionManagement

public

class

TransactionConfig

{

   

    @Bean

   

public

PlatformTransactionManager transactionManager

(

DataSource dataSource

)

{

       

return

new

DataSourceTransactionManager

(

dataSource

)

;

   

}

   

   

// Can define a transaction template

    @Bean

   

public

TransactionTemplate transactionTemplate

(

PlatformTransactionManager manager

)

{

       

return

new

TransactionTemplate

(

manager

)

;

   

}

}

4. Usage conventions and best practices

Mapper interface definition:

Example

@

Repository

// Explicit DAO-layer annotations

public

interface

UserMapper

{

    @Select

(

"SELECT * FROM users WHERE id = #{id}"

)

    User selectById

(

@Param

(

"id"

)

int

id

)

;

   

    @Options

(

useGeneratedKeys

=

true

, keyProperty

=

"id"

)

    @Insert

(

"INSERT INTO users(name) VALUES(#{name})"

)

   

int

insert

(

User user

)

;

}

Service layer example:

Example

@Service

@Transactional

(

readOnly

=

true

)

// Read-only by default

public

class

UserService

{

   

   

private

final

UserMapper userMapper

;

   

    @Autowired

// Constructor injection recommended

   

public

UserService

(

UserMapper userMapper

)

{

       

this

.

userMapper

=

userMapper

;

   

}

   

    @Transactional

// Write operations open a transaction separately

   

public

User createUser

(

String

name

)

{

        User user

=

new

User

(

)

;

        user.

setName

(

name

)

;

        userMapper.

insert

(

user

)

;

       

return

userMapper.

selectById

(

user.

getId

(

)

)

;

   

}

}

5. Advanced feature integration

Dynamic data source configuration:

Example

@Bean

@Primary

public

DataSource dynamicDataSource

(

)

{

    DynamicDataSource ds

=

new

DynamicDataSource

(

)

;

    ds.

setDefaultTargetDataSource

(

primaryDataSource

(

)

)

;

    ds.

setTargetDataSources

(

Map

.

of

(

       

"master"

, primaryDataSource

(

)

,

       

"slave"

, secondaryDataSource

(

)

   

)

)

;

   

return

ds

;

}

Multi-data-source transaction management:

Example

@Bean

public

PlatformTransactionManager transactionManager

(

)

{

   

return

new

ChainedTransactionManager

(

       

new

JpaTransactionManager

(

entityManagerFactory

(

)

)

,

       

new

DataSourceTransactionManager

(

dataSource

(

)

)

   

)

;

}


MyBatis best practices

  1. Use the Mapper interface instead of using SqlSession directly: This makes the code more type-safe and easier to maintain.
  2. Use dynamic SQL appropriately: Avoid SQL injection risks and keep SQL readable.
  3. Batch Operations: For large batch data operations, use batch processing to improve performance.
  4. Use caching appropriately: Configure appropriate caching strategies based on business needs.
  5. SQL optimization: Write efficient SQL statements in the Mapper XML.

MyBatis is a flexible and powerful ORM framework; used properly, it can greatly improve development efficiency and application performance. I hope this article helps you understand and use the MyBatis framework.

Common Java Libraries Common Java Libraries