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

SpringBoot集成mybatis实例

程序员文章站 2024-03-01 10:58:46
一、使用 1、添加依赖 org.mybatis.spring.boot<...

一、使用

1、添加依赖

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

2、启动时导入指定的sql(application.properties)

spring.datasource.schema=import.sql

3、annotation形式

@springbootapplication
@mapperscan("sample.mybatis.mapper")
public class samplemybatisapplication implements commandlinerunner {

  @autowired
  private citymapper citymapper;

  public static void main(string[] args) {
    springapplication.run(samplemybatisapplication.class, args);
  }

  @override
  public void run(string... args) throws exception {
    system.out.println(this.citymapper.findbystate("ca"));
  }

}

4、xml方式

mybatis-config.xml

<?xml version="1.0" encoding="utf-8" ?>
<!doctype configuration
    public "-//mybatis.org//dtd config 3.0//en"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <typealiases>
    <package name="sample.mybatis.domain"/>
  </typealiases>
  <mappers>
    <mapper resource="sample/mybatis/mapper/citymapper.xml"/>
  </mappers>
</configuration>

application.properties

spring.datasource.schema=import.sql
mybatis.config=mybatis-config.xml

mapper

@component
public class citymapper {

  @autowired
  private sqlsessiontemplate sqlsessiontemplate;

  public city selectcitybyid(long id) {
    return this.sqlsessiontemplate.selectone("selectcitybyid", id);
  }

}

二、手工集成

1、annotation方式

@configuration
@mapperscan("com.xixicat.modules.dao")
@propertysources({ @propertysource(value = "classpath:application.properties", ignoreresourcenotfound = true), @propertysource(value = "file:./application.properties", ignoreresourcenotfound = true) })
public class mybatisconfig {
  
  @value("${name:}")
  private string name;

  @value("${database.driverclassname}")
  private string driverclass;

  @value("${database.url}")
  private string jdbcurl;

  @value("${database.username}")
  private string dbuser;

  @value("${database.password}")
  private string dbpwd;

  @value("${pool.minpoolsize}")
  private int minpoolsize;

  @value("${pool.maxpoolsize}")
  private int maxpoolsize;


  @bean
  public filter characterencodingfilter() {
    characterencodingfilter characterencodingfilter = new characterencodingfilter();
    characterencodingfilter.setencoding("utf-8");
    characterencodingfilter.setforceencoding(true);
    return characterencodingfilter;
  }

  @bean(destroymethod = "close")
  public datasource datasource(){
    hikariconfig hikariconfig = new hikariconfig();
    hikariconfig.setdriverclassname(driverclass);
    hikariconfig.setjdbcurl(jdbcurl);
    hikariconfig.setusername(dbuser);
    hikariconfig.setpassword(dbpwd);
    hikariconfig.setpoolname("springhikaricp");
    hikariconfig.setautocommit(false);
    hikariconfig.adddatasourceproperty("cacheprepstmts", "true");
    hikariconfig.adddatasourceproperty("prepstmtcachesize", "250");
    hikariconfig.adddatasourceproperty("prepstmtcachesqllimit", "2048");
    hikariconfig.adddatasourceproperty("useserverprepstmts", "true");
     
    hikariconfig.setminimumidle(minpoolsize);
    hikariconfig.setmaximumpoolsize(maxpoolsize);
    hikariconfig.setconnectioninitsql("select 1");
    
    hikaridatasource datasource = new hikaridatasource(hikariconfig);
    return datasource;
  }
  
  @bean
  public platformtransactionmanager transactionmanager() {
    return new datasourcetransactionmanager(datasource());
  }

  @bean
  public sqlsessionfactory sqlsessionfactory() throws exception {
    sqlsessionfactorybean sessionfactory = new sqlsessionfactorybean();
    sessionfactory.setdatasource(datasource());
    sessionfactory.setfailfast(true);
    sessionfactory.setconfiglocation(new classpathresource("mybatis-config.xml"));
    return sessionfactory.getobject();
  }
}

点评

这种方式有点别扭,而且配置不了拦截式事务拦截,只能采用注解声明,有些冗余

2、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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

  <context:property-placeholder ignore-unresolvable="true" />

  <bean id="hikariconfig" class="com.zaxxer.hikari.hikariconfig">
    <property name="poolname" value="springhikaricp" />
    <property name="connectiontestquery" value="select 1" />
    <property name="datasourceclassname" value="${database.datasourceclassname}" />
    <property name="maximumpoolsize" value="${pool.maxpoolsize}" />
    <property name="idletimeout" value="${pool.idletimeout}" />

    <property name="datasourceproperties">
      <props>
        <prop key="url">${database.url}</prop>
        <prop key="user">${database.username}</prop>
        <prop key="password">${database.password}</prop>
      </props>
    </property>
  </bean>

  <!-- hikaricp configuration -->
  <bean id="datasource" class="com.zaxxer.hikari.hikaridatasource" destroy-method="close">
    <constructor-arg ref="hikariconfig" />
  </bean>

  <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
    <property name="datasource" ref="datasource"/>
    <!-- 配置mybatis配置文件的位置 -->
    <property name="configlocation" value="classpath:mybatis-config.xml"/>
    <property name="typealiasespackage" value="com.xixicat.domain"/>
    <!-- 配置扫描mapper xml的位置 -->
    <property name="mapperlocations" value="classpath:com/xixicat/modules/dao/*.xml"/>


  </bean>

  <!-- 配置扫描mapper接口的包路径 -->
  <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
    <property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/>
    <property name="basepackage" value="com.xixicat.repository.mapper"/>
  </bean>

  <bean id="sqlsessiontemplate" class="org.mybatis.spring.sqlsessiontemplate">
    <constructor-arg ref="sqlsessionfactory"/>
  </bean>

  <bean id="transactionmanager"
     class="org.springframework.jdbc.datasource.datasourcetransactionmanager"
     p:datasource-ref="datasource"/>
  <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />

  <tx:advice id="txadvice" transaction-manager="transactionmanager" >
    <tx:attributes>
      <tx:method name="start*" propagation="required"/>
      <tx:method name="submit*" propagation="required"/>
      <tx:method name="clear*" propagation="required"/>
      <tx:method name="create*" propagation="required"/>
      <tx:method name="activate*" propagation="required"/>
      <tx:method name="save*" propagation="required"/>
      <tx:method name="insert*" propagation="required"/>
      <tx:method name="add*" propagation="required"/>
      <tx:method name="update*" propagation="required"/>
      <tx:method name="delete*" propagation="required"/>
      <tx:method name="remove*" propagation="required"/>
      <tx:method name="execute*" propagation="required"/>
      <tx:method name="del*" propagation="required"/>
      <tx:method name="*" read-only="true"/>
    </tx:attributes>
  </tx:advice>
  <aop:config proxy-target-class="true" expose-proxy="true">
    <aop:pointcut id="pt" expression="execution(public * com.xixicat.service.*.*(..))" />
    <aop:advisor order="200" pointcut-ref="pt" advice-ref="txadvice"/>
  </aop:config>
</beans>

aop依赖

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-aop</artifactid>
    </dependency>

mybatis-spring等依赖

<!-- boot dependency mybatis -->
    <dependency>
      <groupid>org.mybatis</groupid>
      <artifactid>mybatis</artifactid>
      <version>3.3.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupid>org.mybatis</groupid>
      <artifactid>mybatis-spring</artifactid>
      <version>1.2.2</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupid>mysql</groupid>
      <artifactid>mysql-connector-java</artifactid>
      <version>5.1.6</version>
    </dependency>

    <!--<dependency>-->
      <!--<groupid>org.hsqldb</groupid>-->
      <!--<artifactid>hsqldb</artifactid>-->
      <!--<scope>runtime</scope>-->
    <!--</dependency>-->

    <dependency>
      <groupid>com.zaxxer</groupid>
      <artifactid>hikaricp-java6</artifactid>
      <version>2.3.8</version>
    </dependency>

指定xml配置文件

@configuration
@componentscan( basepackages = {"com.xixicat"} )
@importresource("classpath:applicationcontext-mybatis.xml")
@enableautoconfiguration
public class appmain {

  // 用于处理编码问题
  @bean
  public filter characterencodingfilter() {
    characterencodingfilter characterencodingfilter = new characterencodingfilter();
    characterencodingfilter.setencoding("utf-8");
    characterencodingfilter.setforceencoding(true);
    return characterencodingfilter;
  }

  //文件下载
  @bean
  public httpmessageconverters restfiledownloadsupport() {
    bytearrayhttpmessageconverter arrayhttpmessageconverter = new bytearrayhttpmessageconverter();
    return new httpmessageconverters(arrayhttpmessageconverter);
  }

  public static void main(string[] args) throws exception {
    springapplication.run(appmain.class, args);
  }

}

点评

跟传统的方式集成最为直接,而且事务配置也比较容易上手

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。