Getting started with MyBatis and MyBatis Plus

MyBatis

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

  1. Add dependencies
  • mybatis
  • mysql-connector-java
<project ...>
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${latest_version}</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${latest_version}</version>
</dependency>
</dependencies>
</project>
  1. Write the mybatis-config.xml file
  • Configuring the data source.
  • Inject mappers
<configuration>
<environments default="development">
<environment id="development">
<dataSource type="POOLED">
<property name="driver" value="${MYSQL_DRIVER_CLASS}"/>
<property name="url" value="${MYSQL_URL}"/>
<property name="username" value="${MYSQL_USER}"/>
<property name="password" value="${MYSQL_PASSWD}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/mapper/UserMapper.xml" />
</mappers>
</configuration>
  1. Write maper XML file
<mapper>
...
</mapper>
  1. Usage
  • Load mybatis-config.xml
  • Build SqlSessionFactory object
  • Get SqlSession object
  • Get mapper object
  • Call methods of mapper object
public static void main(String[] args) throws IOException {
String resource = "mybatis/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.selectByPrimaryKey(1);
logger.debug("user is {}", user);
}
}

MyBatis with Spring

MyBatis-Spring integrates MyBatis seamlessly with Spring. This library allows MyBatis to participate in Spring transactions, takes care of building MyBatis mappers and SqlSessions and inject them into other beans, translates MyBatis exceptions into Spring DataAccessExceptions, and finally, it lets you build your application code free of dependencies on MyBatis, Spring or MyBatis-Spring.

  1. Add dependencies
  • spring related
  • mybatis
  • mybatis-spring
  • mysql-connector-java
<!-- Spring -->
...
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.jdbc.version}</version>
</dependency>
  1. Write spring-mybatis.xml configuration file
  • Configuring dataSource
  • Configuring sqlSessionFactory for specifying mapper xml files location.
  • Configuring MapperScannerConfigurer for specifying mapper interface Java files location.
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
...
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.taogen.example.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
  1. Write maper XML file
<mapper>
...
</mapper>
  1. Usage
  • Call Dao interface method
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;

@Override
public List<User> listAllUsers() {
return userDao.listAllUsers();
}
...
}

MyBatis with Spring Boot

The MyBatis-Spring-Boot-Starter help you build quickly MyBatis applications on top of the Spring Boot.

By using this module you will achieve:

  • Build standalone applications
  • Reduce the boilerplate to almost zero
  • Less XML configuration

MyBatis-Spring-Boot-Starter will:

  • Autodetect an existing DataSource
  • Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory
  • Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans
  1. Add dependencies
  • mybatis-spring-boot-starter
  • mysql-connector-java
<!-- spring boot -->
...
<!-- data access -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
  1. Write Spring Boot configuration file application.yml
  • Configuring data sources
  • Configuring mybatis for specifying mapper xml files location.
spring:
datasource:
url: jdbc:mysql://localhost:3306/my_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.taogen.demo.springbootcrud.module.*.entity
  1. Write maper XML file
<mapper>
...
</mapper>
  1. Definition mapper interfaces

The MyBatis-Spring-Boot-Starter will search, by default, for mappers marked with the @Mapper annotation.

@Mapper
public interface UserDao {
}

You may want to specify a custom annotation or a marker interface for scanning. If so, you must use the @MapperScan annotation.

@MapperScan(value = "com.taogen.example.dao")

The value attribute is a alias for the basePackages attribute.

  1. Usage
  • Call Dao interface method
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;

@Override
public List<User> listAllUsers() {
return userDao.listAllUsers();
}
...
}

MyBatis Plus with Spring Boot

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑。
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作。
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求。
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错。
  1. Add dependencies
  • mybatis-plus-boot-starter
  • mysql-connector-java
<!-- spring boot -->
...
<!-- data access -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
  1. Write Spring Boot configuration file application.yml
  • Configuring data sources
  • Configuring mybatis for specifying mapper xml files location. (If you just use mybatis plus service and dao method, you needn’t configure this.)
spring:
datasource:
url: jdbc:mysql://localhost:3306/my_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.taogen.demo.springbootcrud.module.*.entity
  1. Write maper XML file

(If you just use mybatis plus service and dao method, you needn’t this.)

<mapper>
...
</mapper>
  1. Definition mapper interfaces

The MyBatis-Spring-Boot-Starter will search, by default, for mappers marked with the @Mapper annotation.

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

@Mapper
public interface UserDao extends BaseMapper<User> {
}

You may want to specify a custom annotation or a marker interface for scanning. If so, you must use the @MapperScan annotation.

@MapperScan(value = "com.taogen.example.dao")

The value attribute is a alias for the basePackages attribute.

  1. extends MyBatis Plus class

dao

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

@Mapper
public interface UserDao extends BaseMapper<User> {
}

service

import com.baomidou.mybatisplus.extension.service.IService;

public interface UserService extends IService<User> {
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
}
  1. Usage
  • Call MyBatis Plus CRUD methods
QueryWrapper<User> queryWrapper = new QueryWrapper();
List<User> userList = userService.list(queryWrapper);

More MyBatis Plus method reference CRUD接口

References

[1] mybatis

[2] mybatis-spring

[3] mybatis-spring-boot-autoconfigure

[4] MyBatis-Plus 快速开始