欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-31 13:12:16
1. 导入依赖的jar包 springboot项目整合mybatis之前首先要导入依赖的jar包,配置pom.xml文件如下:

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

总结

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