Methods Steps and Examples of Integrating mybatis in SpringBoot Project

  • 2021-07-06 11:00:31
  • OfStack

1. Import dependent jar packages

The springboot project first imports the dependent jar package before integrating mybatis, and configures the pom. xml file as follows:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.u</groupId>
  <artifactId>springboot-mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RELEASE</version>
  </parent>
  <properties>
    <start-class>com.us.Application</start-class>
    <mybatis.version>3.2.7</mybatis.version>
    <mybatis-spring.version>1.2.2</mybatis-spring.version>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>
  <dependencies>
    <!--springboot-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--db-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
    </dependency>
    <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>
    <!--util-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
  </dependencies>
</project>

2. Configure the data source

After pom. xml is configured, you need to configure the data source. Create a new DBConfig class configuration data source with the following code:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.base.Preconditions;
@Configuration
public class DBConfig {
  @Autowired
  private Environment env;
  @Bean(name = "dataSource")
  public DruidDataSource dataSource() {
    final String url = Preconditions.checkNotNull(env.getProperty("ms.db.url"));
    final String username = Preconditions.checkNotNull(env.getProperty("ms.db.username"));
    final String password = env.getProperty("ms.db.password");
    final int maxActive = Integer.parseInt(env.getProperty("ms.db.maxActive", "200"));
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setMaxActive(maxActive);
    return dataSource;
  }
}

3. Add database connection information

Add the database connection information to the configuration file application. properties as follows:


ms.db.url=jdbc:mysql://localhost:3306/dev?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=true
ms.db.username=root
ms.db.password=admin
ms.db.maxActive=500

4. Configure SqlSessionFactoryBean for mybatis

After the data source is configured, SqlSessionFactoryBean of mybatis should be configured to scan mapper. The newly created MyBatisConfig class code is as follows (classpath*: mapper/*. xml is the file path of mapper.xml):


import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisConfig {
  @Autowired
  private DataSource dataSource;
  @Bean(name = "sqlSessionFactory")
  public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dataSource);
    sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml"));
    return sessionFactory;
  }
}

5. Configure MapperScannerConfigurer to scan dao layer

Then configure MapperScannerConfigurer to scan the dao layer, and create a new class MyBatisScannerConfig code as follows (note that it should not be written in one class with MyBatisConfig):


import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisScannerConfig {
  @Bean
  public MapperScannerConfigurer MapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setBasePackage("com.example.*.dao");
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    return mapperScannerConfigurer;
  }
}

6. The code for opening a database transaction (must) is as follows


import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
@Configuration
public class TransactionConfig implements TransactionManagementConfigurer{
  @Autowired
  private DataSource dataSource;
  @Bean(name = "transactionManager")
  @Override
  public PlatformTransactionManager annotationDrivenTransactionManager() {
    return new DataSourceTransactionManager(dataSource);
  }
}

7. Actual combat

The configuration is roughly like this, and then the new java bean (omitted, source address at the bottom of the article)

Create a new mapper. xml file (omitted, the source code address at the bottom of the article. For questions about the preparation of mapper. xml file, please see my previous springmvc+mybatis series articles)

Create a new dao layer. The code is as follows:


import java.util.List;
import java.util.Map;
import com.example.base.model.User;
import com.example.config.MyBatisRepository;
public interface UserDao {
  public List<User> getList(Map<String,Object> map);
}

The service layer adds the @ service annotation to the implementation class as follows:


import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.base.dao.UserDao;
import com.example.base.service.UserService;
@Service
public class UserServiceImpl implements UserService {
  @Autowired
  private UserDao userDao;
  public Object getList(Map<String, Object> map) {
    return userDao.getList(map);
  }
}

The controller layer should also be annotated with @ controller code as follows:


import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.base.service.UserService;
import com.example.base.util.CommonUtil;
import com.example.demo.ServiceEmail;
@Controller
@RequestMapping(value = "/users")
public class UserController {
  @Autowired
  private UserService userService;
  @Autowired
  private ServiceEmail serviceEmail;
  /***
   * api :localhost:8099/users?id=99 localhost:8099/users
   * 
   * @param request
   * @return
   */
  @RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
  @ResponseBody
  public ResponseEntity<?> list(HttpServletRequest request) {
    Map<String, Object> map = CommonUtil.getParameterMap(request);
    return new ResponseEntity<Object>(userService.getList(map), HttpStatus.OK);
  }
  }

Then scan the defined configuration tires in the startup entry class (configure the package name instead of writing only part of the package name) as follows:


import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
@ComponentScan(basePackages ="com.example")
@SpringBootApplication
public class Application extends SpringBootServletInitializer{
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
  }
  public static void main(String[] args) throws Exception {
    ApplicationContext ctx = SpringApplication.run(Application.class, args);
    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
      System.out.println(beanName);
    }
  }
}

Summarize


Related articles: