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

Spring Boot整合MyBatis操作过程

程序员文章站 2024-02-26 21:53:34
1.加入mybatis-spring-boot-stater的maven依赖

1.加入mybatis-spring-boot-stater的maven依赖

  <dependency>
      <groupid>org.mybatis.spring.boot</groupid>
      <artifactid>mybatis-spring-boot-starter</artifactid>
      <version>1.1.1</version>
    </dependency>

2.配置数据源

在src/main/resource中,application.properties配置文件中,这里面添加了一些数据库连接的信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.driver

3.代码注入数据源

package com.example;

import javax.sql.datasource;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.web.servlet.filterregistrationbean;
import org.springframework.boot.web.servlet.servletcomponentscan;
import org.springframework.boot.web.servlet.servletlistenerregistrationbean;
import org.springframework.boot.web.servlet.servletregistrationbean;
import org.springframework.context.annotation.bean;
import org.springframework.core.env.environment;
import org.springframework.web.servlet.dispatcherservlet;
import com.alibaba.druid.pool.druiddatasource;
import com.example.listener.indexlistener;
import com.example.filter.indexfilter;
import com.example.servlet.myservlet;
@springbootapplication
public class springbootsimpleapplication {
  @autowired
  private environment env;
  @bean
  public datasource datasource() {
    druiddatasource datasource = new druiddatasource();
    datasource.seturl(env.getproperty("spring.datasource.url"));
    datasource.setusername(env.getproperty("spring.datasource.username"));//用户名
    datasource.setpassword(env.getproperty("spring.datasource.password"));//密码
    datasource.setdriverclassname(env.getproperty("spring.datasource.driver-class-name"));
    datasource.setinitialsize(2);
    datasource.setmaxactive(20);
    datasource.setminidle(0);
    datasource.setmaxwait(60000);
    datasource.setvalidationquery("select 1");
    datasource.settestonborrow(false);
    datasource.settestwhileidle(true);
    datasource.setpoolpreparedstatements(false);
    return datasource;
  }
  public static void main(string[] args) {
    springapplication.run(springbootsimpleapplication.class, args);
  }
}

4.增加mybatis的配置

mybatisconfig.java类:

package com.example.mybatis;
import javax.sql.datasource;
import org.apache.ibatis.session.sqlsessionfactory;
import org.mybatis.spring.sqlsessionfactorybean;
import org.mybatis.spring.sqlsessiontemplate;
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.enabletransactionmanagement;
import org.springframework.transaction.annotation.transactionmanagementconfigurer;
@configuration
//加上这个注解,使得支持事务
@enabletransactionmanagement
public class mybatisconfig implements transactionmanagementconfigurer {
  @autowired
  private datasource datasource;
  @override
  public platformtransactionmanager annotationdriventransactionmanager() {
    return new datasourcetransactionmanager(datasource);
  }
  @bean(name = "sqlsessionfactory")
  public sqlsessionfactory sqlsessionfactorybean() {
    sqlsessionfactorybean bean = new sqlsessionfactorybean();
    bean.setdatasource(datasource);
    try {
      return bean.getobject();
    } catch (exception e) {
      e.printstacktrace();
      throw new runtimeexception(e);
    }
  }
  @bean
  public sqlsessiontemplate sqlsessiontemplate(sqlsessionfactory sqlsessionfactory) {
    return new sqlsessiontemplate(sqlsessionfactory);
  }
}

mybatismapperscannerconfig.java类:

package com.example.mybatis;
import org.mybatis.spring.mapper.mapperscannerconfigurer;
import org.springframework.boot.autoconfigure.autoconfigureafter;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
/**
 * 扫描mybatis的接口
 */
@configuration
// 因为这个对象的扫描,需要在mybatisconfig的后面注入,所以加上下面的注解
@autoconfigureafter(mybatisconfig.class)
public class mybatismapperscannerconfig {
  @bean
  public mapperscannerconfigurer mapperscannerconfigurer() {
    mapperscannerconfigurer mapperscannerconfigurer = new mapperscannerconfigurer();
    //获取之前注入的beanname为sqlsessionfactory的对象
    mapperscannerconfigurer.setsqlsessionfactorybeanname("sqlsessionfactory");
    //指定xml配置文件的路径
    mapperscannerconfigurer.setbasepackage("com.example.mybatis.mapper");
    return mapperscannerconfigurer;
  }
}

5.mybatis接口配置,这里使用student表作为示例

使用@mapper注解来标识一个接口为mybatis的接口,mybatis会自动寻找这个接口

package com.example.mybatis.mapper;
import java.util.list;
import java.util.map;
import org.apache.ibatis.annotations.insert;
import org.apache.ibatis.annotations.mapper;
import org.apache.ibatis.annotations.param;
import org.apache.ibatis.annotations.select;
@mapper
public interface studentmapper {
  @select("select * from student;")
  public list<map<string,object>> find();
  @insert("insert into student(id,name,age,score_sum,score_avg) "+
      "values(#{id},'jim',33,200,100)")
  public int insert(@param("id")int id);
}

6.service业务层调用接口

package com.example.mybatis;
import java.util.list;
import java.util.map;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import com.example.mybatis.mapper.studentmapper;
@service
public class stumybatisservice {
  @autowired
  private studentmapper studentmapper;
  public list<map<string,object>> find(){
    return studentmapper.find();
  }
  public int insert(int id){
    return studentmapper.insert(id);
  }
}

7.controller控制层调用service业务层

package com.example.mybatis;
import java.util.list;
import java.util.map;
import org.apache.logging.log4j.logmanager;
import org.apache.logging.log4j.logger;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
@requestmapping("/stumybatis")
public class stumybatiscontroller {
  private static logger logger = logmanager.getlogger(stumybatiscontroller.class);
  @autowired
  private stumybatisservice stumybatisservice;
  @requestmapping("/list")
  public list<map<string,object>> getstus(){
    logger.info("从数据库读取student集合");
    return stumybatisservice.find();
  }
  @requestmapping("/add")
  public void addstus(){
    logger.info("student表中插入数据");
    stumybatisservice.insert(2);
  }
}

最终启动程序,进行访问:

返回结果:

[{"score_sum":180.0,"name":"张三","id":1,"age":25,"score_avg":90.0},{"score_sum":200.0,"name":"jim","id":2,"age":33,"score_avg":100.0}]

以上所述是小编给大家介绍的spring boot整合mybatis的操作过程,希望对大家有所帮助