(六)Spring Boot整合mybtis

来源:互联网 发布:金数据 - 登录 编辑:程序博客网 时间:2024/06/07 22:30
Spring Boot目前整合Mybatis的方式有两种,一种是Mybatis官方发布的mybatis-spring-boot-starter 一种是将传统的xml 改为java配置的方式. 
数据源使用阿里的druid,并配置druid的监控,开启事务管理,原项目下载:点此下载

引入依赖
<!-- Spring Boot 整合Mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.0</version></dependency><dependency>  <groupId>com.github.pagehelper</groupId>  <artifactId>pagehelper</artifactId>  <version>4.0.0</version>  </dependency> <!-- MySql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--连接池  --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.28</version></dependency>

之前的基于xml的配置 applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"><!-- 数据库连接池 --><!-- 加载配置文件 --><context:property-placeholder location="classpath:properties/*.properties" /><!-- 数据库连接池 --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"destroy-method="close"><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="driverClassName" value="${jdbc.driver}" /><property name="maxActive" value="10" /><property name="minIdle" value="5" /></bean><!-- 配置sqlsessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property><property name="dataSource" ref="dataSource"></property></bean><!-- 配置扫描包,加载mapper代理对象 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.*.*.mapper"></property></bean></beans>

将上面的xml配置 改为基于java的配置
初始化一个Bean,使用@Configuration注解和@Bean之前也有讲过这两个注解的作用,类的名称我们和xml的名称相同
package com.test.springboot.config;import java.sql.SQLException;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;@Configurationpublic class ApplicationContextDao {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Value("${druid.username}")private String druidUsername;@Value("${druid.password}")private String druidPassword;/** * 配置Druid数据源 * @return * @throws SQLException */@Bean(name="dataSource",destroyMethod="close")public DruidDataSource dataSource() throws SQLException{DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);        dataSource.setPassword(password);        //配置最大连接        dataSource.setMaxActive(300);        //配置初始连接        dataSource.setInitialSize(20);        //配置最小连接        dataSource.setMinIdle(10);        //连接等待超时时间        dataSource.setMaxWait(60000);        //间隔多久进行检测,关闭空闲连接        dataSource.setTimeBetweenEvictionRunsMillis(60000);        //一个连接最小生存时间        dataSource.setMinEvictableIdleTimeMillis(300000);        //连接等待超时时间 单位为毫秒 缺省启用公平锁,        //并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁        dataSource.setUseUnfairLock(true);        //用来检测是否有效的sql        dataSource.setValidationQuery("select 'x'");        dataSource.setTestWhileIdle(true);        //申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能        dataSource.setTestOnBorrow(false);        //归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能        dataSource.setTestOnReturn(false);        //打开PSCache,并指定每个连接的PSCache大小启用poolPreparedStatements后,        //PreparedStatements 和CallableStatements 都会被缓存起来复用,        //即相同逻辑的SQL可以复用一个游标,这样可以减少创建游标的数量。        dataSource.setPoolPreparedStatements(true);        dataSource.setMaxOpenPreparedStatements(20);        //配置sql监控的filter        dataSource.setFilters("stat,wall,log4j");        try {            dataSource.init();        } catch (SQLException e) {            throw new RuntimeException("druid datasource init fail");        }        return dataSource;}/**     * druid监控     * @return     */    @Bean    public ServletRegistrationBean druidServlet() {        ServletRegistrationBean reg = new ServletRegistrationBean();        reg.setServlet(new StatViewServlet());        reg.addUrlMappings("/druid/*");        reg.addInitParameter("loginUsername", druidUsername);        reg.addInitParameter("loginPassword", druidPassword);        return reg;    }    /**     * druid监控过滤     * @return     */    @Bean    public FilterRegistrationBean filterRegistrationBean() {        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();        filterRegistrationBean.setFilter(new WebStatFilter());        filterRegistrationBean.addUrlPatterns("/*");        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");        return filterRegistrationBean;    }    }
直接启动项目,然后访问http://localhost:9999/druid 输入用户名密码,显示以下界面



扫描包以及事务解释

扫描的包就不用管了,加入了mybatis-spring-boot-starter的依赖,只要遵守Spring Boot的约定,在标注了@SpringBootApplication的类所在的目录或者子目录下的原Mapper的接口上添加一个@Mapper注解就可以了

事务的话,在引入mybatis-spring-boot-starter的依赖之后,会默认添加spring-boot-starter-jdbc的依赖,然后在需要添加事务的类上,或者方法上添加@Transactional注解就可以了(亲测有效)
注意:
@Transactional注解添加到类上,它下面的所有public的方法事务才会生效,如果添加到方法上,只能添加到public的方法上。


原创粉丝点击