SpringBoot项目整合mybatis的方法步骤与实例

1. 导入依赖的jar包

springboot项目整合mybatis之前首先要导入依赖的jar包,配置pom.xml文件如下:

<?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. 配置数据源

pom.xml配置完毕后需要配置数据源了。新建DBConfig类配置数据源,代码如下:

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. 添加数据库连接信息

在配置文件application.properties中添加数据库连接信息如下:

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. 配置mybatis的SqlSessionFactoryBean

数据源配置完以后要配置mybatis的SqlSessionFactoryBean进行扫描mapper,新建MyBatisConfig类代码如下(classpath*:mapper/*.xml为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. 配置MapperScannerConfigurer扫描dao层

然后配置MapperScannerConfigurer扫描dao层,新建类MyBatisScannerConfig代码如下(注意与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. 开启数据库事务(必须)代码如下

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. 实战

配置大致就是如此,然后就是新建java bean(省略,文章底部有源码地址)

新建mapper.xml文件(省略,文章底部有源码地址,关于mapper.xml 文件编写的疑问可以看我以前的springmvc+mybatis 系列文章)

新建dao层。代码如下:

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);
}

service层要在实现类上添加@service注解,代码如下:

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);
  }
}

controller层也要加@controller注解代码如下:

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);
  }
  }

然后在启动入口类中扫描定义的这些配置累(配置包名可却省只写部分包名)如下:

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);
    }
  }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接

(0)

相关推荐

  • Mybatis模糊查询和动态sql语句的用法

    Mybatis 模糊查询和动态sql语句 模糊查询 对数据库最常用的操作就是查询了,但是如何使用Mybatis进行模糊查询呢?下面先看一个简单的模糊查询 <select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee WHERE emp_name LIKE #{asd} </select> 这是一条伪模糊查询, 因为没有实现真正的模糊 "%&qu

  • MyBatis异常-Property 'configLocation' not specified, using default MyBatis Configuration

    配置文件如下: base-context.xml文件如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http

  • MyBatis insert操作插入数据之后返回插入记录的id

    MyBatis插入数据的时候,返回该记录的id <insert id="insert" keyProperty="id" useGeneratedKeys="true"
 parameterType="com.demo.domain.CountRateConfig">
 insert into query_rate_config (code,partner_type,search_count, booking_co

  • eclipse下整合springboot和mybatis的方法步骤

    1.新建maven项目 先新建一个maven项目,勾选上creat a simple project,填写groupid,artifactid 2.建立项目结构 3.添加依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE<

  • mysql+spring+mybatis实现数据库读写分离的代码配置

    场景:一个读数据源一个读写数据源. 原理:借助spring的[org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource]这个抽象类实现,看名字可以了解到是一个路由数据源的东西,这个类中有一个方法 /** * Determine the current lookup key. This will typically be * implemented to check a thread-bound transaction

  • mybatis动态sql之Map参数的讲解

    mybatis 动态sql之Map参数 Mapper文件: <mapper namespace="com.cn.shoje.oa.modules.logistics.dao.PurcDao"> <select id="findAll" parameterType="Map" resultType="Purchase"> select * from prod_purchase where 1=1 <

  • Mybatis MapperScannerConfigurer自动扫描Mapper接口生成代理注入到Spring的方法

    前言 Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring Mybatis在与Spring集成的时候可以配置 MapperFactoryBean来生成Mapper接口的代理. 例如: <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mappe

  • mybatis利用association或collection传递多参数子查询

    有时候我们在查询数据库时,需要以查询结果为查询条件进行关联查询. 在mybatis 中通过 association 标签(一对一查询,collection 一对多 查询) 实现延迟加载子查询 <resultMap id="xxxMap" type="xxxx.bean.xxx" extends="zzzzMap"> <association property="destName" javaType="

  • 简单易懂的MyBatis分库分表方案分享

    前言 数据库分库分表除了使用中间件来代理请求分发之外,另外一种常见的方法就是在客户端层面来分库分表 -- 通过适当地包装客户端代码使得分库分表的数据库访问操作代码编写起来也很方便.本文的分库分表方案基于 MyBatis 框架,但是又不同于市面上常用的方案,它们一般都是通过编写复杂的 MyBatis 插件来重写 SQL 语句,这样的插件代码会巨复杂无比,可能最终只有插件的原作者自己可以完全吃透相关代码,给项目的维护性带来一定问题.本文的方案非常简单易懂,而且也不失使用上的便捷性.它的设计哲学来源于

  • Mybatis下动态sql中##和$$的区别讲解

    一.介绍 mybatis 中使用 Mapper.xml里面的配置进行 sql 查询,经常需要动态传递参数,例如我们需要根据用户的姓名来筛选用户时,sql 如下: select * from user where name = "Jack"; 上述 sql 中,我们希望 name 后的参数 "Jack" 是动态可变的,即不同的时刻根据不同的姓名来查询用户.在 Mapper.xml文件中使用如下的 sql 可以实现动态传递参数 name: select * from u

随机推荐