Skip to content

Commit

Permalink
更改Mybatis设置,加入Mybatis Plus,设置多数据源
Browse files Browse the repository at this point in the history
  • Loading branch information
xwj-vic committed Mar 27, 2017
1 parent 32a3f18 commit 65cbeab
Show file tree
Hide file tree
Showing 12 changed files with 283 additions and 37 deletions.
33 changes: 23 additions & 10 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,23 +47,36 @@
</dependency>

<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>

<!--2.dao框架:MyBatis依赖-->
<!--<dependency>-->
<!--<groupId>org.mybatis</groupId>-->
<!--<artifactId>mybatis</artifactId>-->
<!--<version>3.4.1</version>-->
<!--</dependency>-->

<!--&lt;!&ndash;mybatis自身实现的spring整合依赖&ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.mybatis</groupId>-->
<!--<artifactId>mybatis-spring</artifactId>-->
<!--<version>1.3.0</version>-->
<!--</dependency>-->

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.0.5</version>
</dependency>

<!--mybatis自身实现的spring整合依赖-->
<!--自动生成代码-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

<!--3.Servlet web相关依赖-->
Expand Down
8 changes: 3 additions & 5 deletions src/main/java/dao/ShiroUserDao.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
* Created by xuweijie on 2017/3/7.
*/
public interface ShiroUserDao {
public User queryByName(String username);
public interface ShiroUserDao extends BaseMapper<User> {
User queryByName(String username);
}
7 changes: 6 additions & 1 deletion src/main/java/entity/User.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package entity;

import com.baomidou.mybatisplus.annotations.TableName;

import java.io.Serializable;

/**
* Created by xuweijie on 2017/3/7.
*/
public class User {
@TableName("User")
public class User implements Serializable {
private int id;
private String username;
private String password;
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/service/ShiroUserService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package service;

import com.baomidou.mybatisplus.service.IService;
import entity.User;

import java.util.List;
Expand All @@ -8,6 +9,6 @@
* 认证授权服务接口
* Created by xuweijie on 2017/3/3.
*/
public interface ShiroUserService {
public User queryUser(String username);
public interface ShiroUserService extends IService<User> {
User queryUser(String username);
}
3 changes: 2 additions & 1 deletion src/main/java/service/impl/ShiroUserServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import dao.ShiroUserDao;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -10,7 +11,7 @@
* Created by xuweijie on 2017/3/6.
*/
@Service
public class ShiroUserServiceImpl implements ShiroUserService {
public class ShiroUserServiceImpl extends ServiceImpl<ShiroUserDao,User> implements ShiroUserService {

@Autowired
private ShiroUserDao userDao;
Expand Down
17 changes: 17 additions & 0 deletions src/main/java/util/datasource/DBTypeEnum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package util.datasource;

/**
* Created by xuweijie on 17-3-26.
*/
public enum DBTypeEnum {
one("dataSourceOne"),tow("dataSourceTwo");
private String value;

DBTypeEnum(String value) {
this.value = value;
}

public String getValue() {
return value;
}
}
32 changes: 32 additions & 0 deletions src/main/java/util/datasource/DbContextHolder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package util.datasource;

import com.baomidou.mybatisplus.enums.DBType;

/**
* Created by xuweijie on 17-3-26.
*/
public class DbContextHolder {

private static final ThreadLocal contextHolder = new ThreadLocal<>();

/**
* 设置数据源
*/
public static void setDbType(DBTypeEnum dbTypeEnum) {
contextHolder.set(dbTypeEnum.getValue());
}

/**
* 取得当前数据源
*/
public static String getDbType() {
return (String) contextHolder.get();
}

/**
* 清除上下文数据
*/
public static void clearDbType() {
contextHolder.remove();
}
}
18 changes: 18 additions & 0 deletions src/main/java/util/datasource/DynamicDataSource.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package util.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
* Created by xuweijie on 17-3-26.
*/
public class DynamicDataSource extends AbstractRoutingDataSource {

/**
* 取得当前使用哪个数据源
* @return
*/
protected Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}

2 changes: 1 addition & 1 deletion src/main/resources/jdbc.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

validationQuery=SELECT 1
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://120.25.79.159:3306/SSMDB?autoReconnect=true&useUnicode=true&characterEncoding=utf8
jdbc.username=xuweijie
Expand Down
25 changes: 25 additions & 0 deletions src/main/resources/mybatis-config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,38 @@
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--
| 全局配置设置
|
| 可配置选项 默认值, 描述
|
| aggressiveLazyLoading true, 当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。
| multipleResultSetsEnabled true, 允许和不允许单条语句返回多个数据集(取决于驱动需求)
| useColumnLabel true, 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。
| useGeneratedKeys false, 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。
| autoMappingBehavior PARTIAL, 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。
| defaultExecutorType SIMPLE, 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。
| defaultStatementTimeout null, 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时
| -->


<settings>
<!--使用jdbc的useGeneratedKeys 获取数据库自增主键值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用列别名替换列名,默认为true-->
<setting name="useColumnLabel" value="true"/>
<!--开启驼峰命名转换Table:create_time到 Entity(createTime)-->
<setting name="mapUnderscoreToCamelCase" value="true"/>

<!-- 这个配置使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="defaultExecutorType" value="REUSE"/>
<setting name="defaultStatementTimeout" value="25000"/>

</settings>

</configuration>
141 changes: 126 additions & 15 deletions src/main/resources/spring/spring-mybatis.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,152 @@
<context:property-placeholder location="classpath:jdbc.properties"/>

<!--2.数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--数据源1-->
<bean id="dataSourceOne" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!--配置连接池属性-->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>

<!--c3p0连接池的私有属性-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--关闭链接后不自动commit-->
<property name="autoCommitOnClose" value="false"/>
<!--获取链接超时时间-->
<property name="checkoutTimeout" value="1000"/>
<!--当获取链接失败重试的次数-->
<property name="acquireRetryAttempts" value="2"/>
<!-- 初始化连接大小 -->
<property name="initialSize" value="0"/>
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20"/>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20"/>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0"/>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000"/>
<property name="validationQuery" value="${validationQuery}"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="testWhileIdle" value="true"/>

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000"/>
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true"/>
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800"/>
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true"/>
<!-- 监控数据库 -->
<property name="filters" value="mergeStat"/>
</bean>

<!--数据源2-->
<bean id="dataSourceTwo" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!--配置连接池属性-->
<property name="driverClassName" value="${jdbc.driver.slave}"/>
<property name="url" value="${jdbc.url.slave}"/>
<property name="username" value="${jdbc.username.slave}"/>
<property name="password" value="${jdbc.password.slave}"/>

<!-- 初始化连接大小 -->
<property name="initialSize" value="0"/>
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20"/>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20"/>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0"/>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000"/>
<property name="validationQuery" value="${validationQuery}"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="testWhileIdle" value="true"/>

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000"/>
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true"/>
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800"/>
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true"/>
<!-- 监控数据库 -->
<property name="filters" value="mergeStat"/>
</bean>

<bean id="dataSource" class="util.datasource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSourceOne" value-ref="dataSourceOne" />
<entry key="dataSourceTwo" value-ref="dataSourceTwo" />
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceOne"/>
</bean>

<!--约定大于配置-->
<!--3.配置SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--org.mybatis.spring.SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<!--往下才是mybatis和spring真正整合的配置-->
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis全局配置文件:mybatis-config.xml-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--扫描sql配置文件:mapper需要的xml文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>

<!-- 插件配置 -->
<property name="plugins">
<array>
<!-- 分页插件配置 -->
<bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
<!-- 指定数据库方言 -->
<property name="dialectType" value="mysql"/>
<property name="optimizeType" value="aliDruid"/>
</bean>
<!-- 如需要开启其他插件,可配置于此 -->
</array>
</property>
<!-- MP 全局配置注入 -->
<property name="globalConfig" ref="globalConfig"/>
</bean>

<!-- 定义 MP 全局策略 -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!-- 主键策略配置 -->
<!-- 可选参数
AUTO->`0`("数据库ID自增")
INPUT->`1`(用户输入ID")
ID_WORKER->`2`("全局唯一ID")
UUID->`3`("全局唯一ID")
-->
<property name="idType" value="2"/>

<!-- 数据库类型配置 -->
<!-- 可选参数(默认mysql)
MYSQL->`mysql`
ORACLE->`oracle`
DB2->`db2`
H2->`h2`
HSQL->`hsql`
SQLITE->`sqlite`
POSTGRE->`postgresql`
SQLSERVER2005->`sqlserver2005`
SQLSERVER->`sqlserver`
-->
<!-- Oracle需要添加该项 -->
<!--<property name="dbType" value="oracle"/>-->
<!--全局表为下划线命名设置 true-->
<!--<property name="dbColumnUnderline" value="true"/>-->
</bean>

<!--4:配置扫描Dao接口包,动态实现DAO接口,注入到spring容器-->
<!--org.mybatis.spring.mapper.MapperScannerConfigurer-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
<!-- 给出需要扫描的Dao接口-->
<property name="basePackage" value="dao"/>
</bean>
Expand Down
Loading

0 comments on commit 65cbeab

Please sign in to comment.