mybatis連線資料庫的幾種方式

我是壞男孩發表於2017-03-13

1.可以通過配置檔案

<?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:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-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/mvc                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- 自動掃描 -->  
    <context:component-scan base-package="gamedataserver"></context:component-scan>
    <!-- 引入配置檔案 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        <!-- 初始化連線大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 連線池最大數量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 連線池最大空閒 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 連線池最小空閒 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 獲取連線最大等待時間 -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </bean> 
    
       <bean id="dataSourceEx" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
         <!-- 資料庫基本資訊配置 -->
         <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${urlEx}" />  
        <property name="username" value="${usernameEx}" />  
        <property name="password" value="${passwordEx}" />  
        <!-- 初始化連線大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 連線池最大數量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 連線池最大空閒 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 連線池最小空閒 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 獲取連線最大等待時間 -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </bean>
    
    <bean id="dataSourceThree" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
         <!-- 資料庫基本資訊配置 -->
         <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${urlThree}" />  
        <property name="username" value="${usernameThree}" />  
        <property name="password" value="${passwordThree}" />  
        <!-- 初始化連線大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 連線池最大數量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 連線池最大空閒 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 連線池最小空閒 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 獲取連線最大等待時間 -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </bean>
  
    <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案          第一個資料庫連結-->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自動掃描mapping.xml檔案 -->  
        <property name="mapperLocations" value="classpath:gamedataserver/mapping/one/*.xml"></property>  
    </bean>  
    
    
      <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案          第二個資料庫連結 -->  
    <bean id="sqlSessionFactoryEx" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSourceEx" />
        <!-- mapper掃描 -->
         <property name="mapperLocations" value="classpath:gamedataserver/mapping/two/*.xml"></property> 
    </bean>

     <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案          第二個資料庫連結 -->  
    <bean id="sqlSessionFactoryThree" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSourceThree" />
        <!-- mapper掃描 -->
         <property name="mapperLocations" value="classpath:gamedataserver/mapping/three/*.xml"></property> 
    </bean>
  
    <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="gamedataserver.dao.one" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>
    
     <!-- DAOEx介面所在包名,Spring會自動查詢其下的類 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="gamedataserver.dao.two" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryEx"></property>  
    </bean>
    
    <!-- DAOEx介面所在包名,Spring會自動查詢其下的類 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="gamedataserver.dao.three" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryThree"></property>  
    </bean>
  
    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->

    <bean name="transactionManagerEx"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSourceEx"></property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <bean id="transactionManagerThree"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSourceThree" />
    </bean>
    
     <!-- 配置自定義Realm -->
    <bean id="myRealm" class="shiro.MyRealm"/>
    
    
    
   
    
    
    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm"/>
    </bean>

    <!-- Shiro過濾器 核心-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全介面,這個屬性是必須的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份認證失敗,則跳轉到登入頁面的配置 -->
        <property name="loginUrl" value="/jsp/admin/loginIndex.jsp"/>
        <!-- 許可權認證失敗,則跳轉到指定頁面 -->
        <property name="unauthorizedUrl" value="/jsp/admin/nopower.jsp"/>
        <!-- Shiro連線約束配置,即過濾鏈的定義 -->
        <property name="filterChainDefinitions">
            <value>
                <!--anon 表示匿名訪問,不需要認證以及授權-->
                /css/=anon
                /js/=anon
                /fonts/=anon
                /img/=anon
                /loginIndex=anon
                
                <!--authc表示需要認證 沒有進行身份認證是不能進行訪問的-->
                /jsp/sysconfig/*=authc,roles[superadmin]
                /jsp/moneyRecord/*=authc
                /jsp/index.jsp=authc,roles[superadmin]
                /jsp/index_player.jsp=authc,roles[admin]
            </value>
        </property>
    </bean>

    <!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 開啟Shiro註解 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
</beans>  

這裡有三個資料來源

2.可以通過註解(不需要mapping.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> 
<!-- 
<properties resource="mybatis/jdbc.properties"/> 
--> 

<typeAliases> 
<typeAlias alias="Player" type="gamedataserver.model.Player"/>
<typeAlias alias="ServerConfig" type="gamedataserver.model.ServerConfig"/>
</typeAliases> 

<environments default="development"> 
<environment id="development"> 
<transactionManager type="JDBC"/> 
<dataSource type="POOLED"> 
<property name="driver" value="${jdbc.driver}"/> 
<property name="url" value="${jdbc.url}"/> 
<property name="username" value="${jdbc.username}"/> 
<property name="password" value="${jdbc.password}"/> 
</dataSource> 
</environment> 
</environments> 
<mappers> 
<mapper class="gamedataserver.dao.one.PlayerMapper"/> 
<mapper class="gamedataserver.dao.two.ServerConfigMapper"/> 
</mappers>
</configuration>

 

 

package gamedataserver.dao.one;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import gamedataserver.model.Player;

public interface PlayerMapper {
	@Delete( "DELETE FROM tbl_Player where id=#{id}")
    int deleteByPrimaryKey(Long id);

    int insert(Player record);

    int insertSelective(Player record);
    @Select("SELECT * FROM tbl_Player where id=#{id}")
    Player selectByPrimaryKey(Long id);
    
    int updateByPrimaryKeySelective(Player record);
    @Update("update tbl_Player set UserName = #{username,jdbcType=VARCHAR} ,UserPass = #{userpass,jdbcType=VARCHAR},"
      +"SessionKey = #{sessionkey,jdbcType=VARCHAR},"
      +"GameMoney = #{gamemoney,jdbcType=BIGINT},"
      +"RealName = #{realname,jdbcType=VARCHAR},"
      +"OpenRoomFreeTimes = #{openroomfreetimes,jdbcType=INTEGER},"
      +"IsMember = #{ismember,jdbcType=INTEGER},"
      +"UnionId = #{unionid,jdbcType=VARCHAR},"
      +"HeadUrl = #{headurl,jdbcType=VARCHAR},"
      +"Sex = #{sex,jdbcType=INTEGER},"
      +"Diamond = #{diamond,jdbcType=INTEGER},"
      +"GoldenFlowerCard = #{goldenflowercard,jdbcType=INTEGER},"
      +"BullCard = #{bullcard,jdbcType=INTEGER},"
      +"MahjongCard = #{mahjongcard,jdbcType=INTEGER},"
      +"LoginTime = #{logintime,jdbcType=BIGINT},"
      +"LogoutTime = #{logouttime,jdbcType=BIGINT},"
      +"CreateTime = #{createtime,jdbcType=BIGINT},"
      +"IsOnLine = #{isonline,jdbcType=INTEGER},"
      +"Version = #{version,jdbcType=VARCHAR} "
      +"where ID = #{id,jdbcType=BIGINT}")
    int updateByPrimaryKey(Player record);
    @Select("SELECT * FROM tbl_Player")
    public List<Player> selectAllPlayer();
    //這個是start limit
    List<Player> selectPlayerByStartLimit(Map params);
    //這個是 where
    int selectPlayerByWhere(Map params);
    @Select("SELECT count(*) FROM tbl_Player where CreateTime>=#{timeStartStamp} and CreateTime<=#{timeEndStamp}")
    int selectPlayerCountByCreateTime(Map<String,Long> map);
}

 

鼓勵:覺得寫得有幫助就支付寶掃一下吧,對你沒有損失,也給我動力

相關文章