SpringMVC4+MyBatis+SQL Server2014 基於SqlSession實現讀寫分離(也能夠實現主從分離)

前言

    上篇文章我覺的使用攔截器雖然方便快捷,可是在使用讀串仍是寫串上你沒法控制,我更但願咱們像jdbc那樣能夠手動控制我使用讀寫串,那麼這篇則在sqlsession的基礎上實現讀寫分離, 這種方式則須要手動實現daoImpl。java

 

項目結構

開發環境

  SpringMVC+MyBatis+SQL Server2014web

 

實現讀寫分離

一、關鍵點是springmvc-servlet.xml中的配置,datasource、sqlsessionfactory、sqlsessionspring

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:mvc="http://www.springframework.org/schema/mvc"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xsi:schemaLocation="http://www.springframework.org/schema/beans
 8        http://www.springframework.org/schema/beans/spring-beans.xsd
 9        http://www.springframework.org/schema/context
10        http://www.springframework.org/schema/context/spring-context.xsd
11        http://www.springframework.org/schema/mvc
12        http://www.springframework.org/schema/mvc/spring-mvc.xsd
13        http://www.springframework.org/schema/tx
14        http://www.springframework.org/schema/tx/spring-tx.xsd">
15 
16     <!--從配置文件加載數據庫信息-->
17     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
18         <property name="locations" value="classpath:config/jdbc.properties"/>
19         <property name="fileEncoding" value="UTF-8"/>
20     </bean>
21 
22     <!--配置數據源,這裏使用Spring默認-->
23     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
24         <property name="driverClassName" value="${sqlserver.driver}"/>
25         <property name="url" value="${sqlserver.url}"/>
26         <property name="username" value="${sqlserver.username}"/>
27         <property name="password" value="${sqlserver.password}"/>
28     </bean>
29 
30 
31     <!--配置sqlSessionFactory-->
32     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
33         <property name="configLocation" value="classpath:springmvc-mybatis.xml"/>
34         <property name="dataSource" ref="dataSource"/>
35     </bean>
36 
37     <!--master-->
38     <bean id="masterSqlSession" class="org.mybatis.spring.SqlSessionTemplate">
39         <constructor-arg index="0" ref="sqlSessionFactory"/>
40     </bean>
41 
42     <!--slave-->
43     <bean id="slaveSqlSession" class="org.mybatis.spring.SqlSessionTemplate">
44         <constructor-arg index="0" ref="sqlSessionFactory"/>
45     </bean>
46 
47     <!--事務管理器 -->
48     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
49         <property name="dataSource" ref="dataSource"/>
50     </bean>
51 
52     <!-- 使用註解事務,須要在Service方法中添加Transactional註解屬性 -->
53     <tx:annotation-driven transaction-manager="transactionManager"/>
54 
55     <!--掃描Mapper-->
56     <!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
57         <!--<property name="basePackage" value="com.autohome.dao"/>-->
58     <!--</bean>-->
59 
60     <!--啓用最新的註解器、映射器-->
61     <mvc:annotation-driven/>
62 
63 
64     <context:component-scan base-package="com.autohome.*"/>
65 
66     <!--jsp視圖解析器-->
67     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
68         <property name="prefix" value="/WEB-INF/views/"/>
69         <property name="suffix" value=".jsp"/>
70     </bean>
71 
72 </beans>

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

<?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>

三、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);
    }
}

四、Serivcespring-mvc

@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);
    }


}

  

總結

     在controller中調用service方法時則能夠看出當前方法使用的鏈接串,並且不用去關心sqlsession的打開關閉問題。session

 

補充

     一開始只站在demo的角度去想sqlsession主從分離或者讀寫分離,從實際應用角度的話從datasource就要分開,而且使用不一樣的讀寫鏈接串。那麼針對如上的配置就是須要配置read-datasource、write-datasource、readsqlsessionfactory、writesqlsessionfactory、readsqlsession、writesqlsession。mybatis

相關文章
相關標籤/搜索