SpringMVC4+MyBatis+SQL Server2014 基于SqlSession实现读写分离(也可以实现主从分离)

时间:2023-01-22 18:29:43

前言

上篇文章我觉的使用拦截器虽然方便快捷,但是在使用读串还是写串上你无法控制,我更希望我们像jdbc那样可以手动控制我使用读写串,那么这篇则在sqlsession的基础上实现读写分离, 这种方式则需要手动实现daoImpl。

项目结构

SpringMVC4+MyBatis+SQL Server2014 基于SqlSession实现读写分离(也可以实现主从分离)

开发环境

SpringMVC+MyBatis+SQL Server2014

实现读写分离

1、关键点是springmvc-servlet.xml中的配置,datasource、sqlsessionfactory、sqlsession

 <?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--从配置文件加载数据库信息-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:config/jdbc.properties"/>
<property name="fileEncoding" value="UTF-8"/>
</bean> <!--配置数据源,这里使用Spring默认-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${sqlserver.driver}"/>
<property name="url" value="${sqlserver.url}"/>
<property name="username" value="${sqlserver.username}"/>
<property name="password" value="${sqlserver.password}"/>
</bean> <!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:springmvc-mybatis.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean> <!--master-->
<bean id="masterSqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean> <!--slave-->
<bean id="slaveSqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean> <!--事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 使用注解事务,需要在Service方法中添加Transactional注解属性 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!--扫描Mapper-->
<!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
<!--<property name="basePackage" value="com.autohome.dao"/>-->
<!--</bean>--> <!--启用最新的注解器、映射器-->
<mvc:annotation-driven/> <context:component-scan base-package="com.autohome.*"/> <!--jsp视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean> </beans>

2、UserMapper.xml。 namespace不再和dao的包名保持一致

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mapper.UserDao">
<select id="listAllUser" resultType="User">
select * from t_userinfo
</select> <select id="listPagedUser" resultType="User">
select top ${pageSize} * from t_userinfo where id not in (select top (${pageSize} * (${pageIndex} -1)) id from t_userinfo)
</select> <select id="count" resultType="int">
select count(*) from t_userinfo
</select> <insert id="insertUser" parameterType="User">
insert into t_userinfo(name,address) VALUES (#{name},#{address})
</insert> <update id="updateUser" parameterType="User">
UPDATE t_userinfo set name=#{name},address=#{address} where id=#{id}
</update> <delete id="deleteUser" parameterType="int">
DELETE FROM t_userinfo where id=#{id}
</delete> <select id="getUserById" resultType="User" parameterType="int">
select * from t_userinfo where id=#{id}
</select> </mapper>

3、UserDao 接口、UserDao实现

public interface UserDao {
List<User> listAllUser();
int insertUser(User user);
User getUserById(int id);
}
@Repository("userDaoImpl")
public class UserDaoImpl implements UserDao { @Autowired
private SqlSession masterSqlSession; @Autowired
private SqlSession slaveSqlSession; public List<User> listAllUser() {
System.out.println("===========slave==========");
return slaveSqlSession.selectList("mapper.UserDao.listAllUser");
} public int insertUser(User user) {
System.out.println("===========master==========");
return masterSqlSession.insert("mapper.UserDao.insertUser",user);
} public User getUserById(int id) {
System.out.println("===========slave==========");
return slaveSqlSession.selectOne("mapper.UserDao.getUserById",id);
}
}

4、Serivce

@Service
public class UserService { @Autowired
@Qualifier("userDaoImpl")
UserDao userDao; public List<User> listAllUser() { return userDao.listAllUser();
} @Transactional
public int insertUser(User user) {
return userDao.insertUser(user);
} public User getUserById(int id) {
return userDao.getUserById(id);
} }

  SpringMVC4+MyBatis+SQL Server2014 基于SqlSession实现读写分离(也可以实现主从分离)

总结

在controller中调用service方法时则可以看出当前方法使用的连接串,而且不用去关心sqlsession的打开关闭问题。

补充

一开始只站在demo的角度去想sqlsession主从分离或者读写分离,从实际应用角度的话从datasource就要分开,并且使用不同的读写连接串。那么针对如上的配置就是需要配置read-datasource、write-datasource、readsqlsessionfactory、writesqlsessionfactory、readsqlsession、writesqlsession。