1. 程式人生 > >SpringMVC+Mybatis+mybatis-generator快速開發架構

SpringMVC+Mybatis+mybatis-generator快速開發架構

這個是我自己搭建使用的架構,對於中小型專案使用該架構還是沒有什麼問題的,但是對於大型架構那麼這個就不要去使用了,話不多說,直接開始架構步驟吧!

1.首先是Maven pom.xml

使用到的架包主要是spring裡面的核心架包,以及mybatis的核心架包,對於資料分頁我選擇使用了com.github.pagehelper,它是一款mybatis外掛,直接在mybaits-config.xml配置即可,這個之後後會介紹,資料來源我們使用阿里的druid,許可權管理則使用apache shrio。

<dependencies>
    <!-- mybatis與spring整合架包 -->
	    <dependency>
		  <groupId>org.mybatis</groupId>
		  <artifactId>mybatis-spring</artifactId>
		  <version>1.2.3</version>
		</dependency>
		<!--  mybastis架包 -->
		<dependency>
		  <groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.3.0</version>
		</dependency>
		
		<!-- pringmvc 架包 -->
		<dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring-web</artifactId>
		  <version>4.2.4.RELEASE</version>
		</dependency>
		
		<!-- mybatis分頁架包 -->
		<dependency>
		  <groupId>com.github.pagehelper</groupId>
		  <artifactId>pagehelper</artifactId>
		  <version>4.1.0</version>
		</dependency>
		
		
		<!-- net.sf.json -->
		<dependency>
		  <groupId>net.sf.json-lib</groupId>
		  <artifactId>json-lib</artifactId>
		  <version>2.4</version>
		</dependency>
		
		<!-- pring webmvc -->
		<dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring-webmvc</artifactId>
		  <version>4.2.4.RELEASE</version>
		</dependency>
		
		<!-- spring-tx -->
		<dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring-tx</artifactId>
		  <version>4.2.4.RELEASE</version>
		</dependency>
		
		<!-- c3p0 -->
		<dependency>
		  <groupId>org.hibernate</groupId>
		  <artifactId>hibernate-c3p0</artifactId>
		  <version>4.3.0.Beta3</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.1.0</version>
		</dependency>
		
		<!-- jsp -->
		<dependency>
		  <groupId>javax.servlet.jsp</groupId>
		  <artifactId>jsp-api</artifactId>
		  <version>2.2.1-b03</version>
		</dependency>
		
		<!-- servletAPI -->
 	   <dependency>
		  <groupId>javax.servlet</groupId>
		  <artifactId>servlet-api</artifactId>
		  <version>3.0-alpha-1</version>
		</dependency>
		
		
		<!-- spring jdbc -->
		<dependency>
		  <groupId>org.springframework</groupId>
		  <artifactId>spring-jdbc</artifactId>
		  <version>4.2.4.RELEASE</version>
		</dependency>
		
		<!-- common-fileupload -->
		<dependency>
		  <groupId>commons-fileupload</groupId>
		  <artifactId>commons-fileupload</artifactId>
		  <version>1.3.1</version>
		</dependency>
		
		<!-- aspectjweaver -->
		<dependency>
		  <groupId>org.aspectj</groupId>
		  <artifactId>aspectjweaver</artifactId>
		  <version>1.8.7</version>
		</dependency>
		
		
		<!-- shiro -->
		<dependency>
		  <groupId>org.apache.shiro</groupId>
		  <artifactId>shiro-web</artifactId>
		  <version>1.2.4</version>
		</dependency>
		
		<dependency>
		  <groupId>org.apache.shiro</groupId>
		  <artifactId>shiro-core</artifactId>
		  <version>1.2.4</version>
		</dependency>
		
		<!-- shiro-spring -->
		<dependency>
		  <groupId>org.apache.shiro</groupId>
		  <artifactId>shiro-spring</artifactId>
		  <version>1.2.4</version>
		</dependency>
		
		<!-- shiro-ehcache -->
		<dependency>
		  <groupId>org.apache.shiro</groupId>
		  <artifactId>shiro-ehcache</artifactId>
		  <version>1.2.4</version>
		</dependency>
		
		<!-- Oracle驅動包 -->	
		<dependency>
	    <groupId>com.oracle</groupId>
	    <artifactId>ojdbc6</artifactId>
	    <version>1.0</version>
	</dependency>
	
	<dependency>
	    <groupId>org.mybatis.generator</groupId>
	    <artifactId>mybatis-generator-core</artifactId>
	    <version>1.3.2</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/log4j/log4j -->
	<dependency>
	    <groupId>log4j</groupId>
	    <artifactId>log4j</artifactId>
	    <version>1.2.17</version>
	</dependency>
		
	<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
	<dependency>
	    <groupId>org.apache.poi</groupId>
	    <artifactId>poi</artifactId>
	    <version>3.15</version>
	</dependency>

2.spring配置檔案

在bean.xml中主要是dataSource等例項進行配置,在加上 service與dao層的物件例項,其中我將service與dao層進行檔案分離而已,這樣層次清洗,程式碼如下!

<?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:aop="http://www.springframework.org/schema/aop"
	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-4.2.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.2.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
         http://www.springframework.org/schema/tx 
         http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
         
    	
    
    	<context:property-placeholder location="classpath:jdbc.properties"/>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
       
        <property name="url" value="${jdbc.url}" />  
	    <property name="username" value="${jdbc.username}" />  
	    <property name="password" value="${jdbc.password}" />  
	        
	    <!-- 配置初始化大小、最小、最大 -->  
	    <property name="initialSize" value="20" />  
	    <property name="minIdle" value="10" />   
	    <property name="maxActive" value="100" />  
	   
	    <!-- 配置獲取連線等待超時的時間 -->  
	    <property name="maxWait" value="60000" />  
	   
	    <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->  
	    <property name="timeBetweenEvictionRunsMillis" value="60000" />  
	   
	    <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->  
	    <property name="minEvictableIdleTimeMillis" value="300000" />  
	    
	    <property name="validationQuery" value="SELECT 'x'" />  
	    <property name="testWhileIdle" value="true" />  
	    <property name="testOnBorrow" value="false" />  
	    <property name="testOnReturn" value="false" />  
	   
	    <!-- 開啟PSCache,並且指定每個連線上PSCache的大小 -->  
	    <property name="poolPreparedStatements" value="true" />  
	    <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />  
	   
	    <!-- 配置監控統計攔截的filters,去掉後監控介面sql無法統計 -->  
	    <property name="filters" value="stat" />
        
    </bean>
    
    <bean id="druid-stat-interceptor"
        class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
        scope="prototype">
        <property name="patterns">
            <list>
                <value>com.goldenbridge.official.service.*</value>
                <value>com.goldenbridge.official.dao.*</value>
            </list>
        </property>
    </bean>
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    </aop:config>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 宣告式事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"
        proxy-target-class="true" />

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>  
    </bean>
    
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">   
          <constructor-arg index="0" ref="sqlSessionFactory" />   
    </bean>

	<!-- 開啟Spring的Annotation支援 -->
		<context:annotation-config />
	
	<import resource="classpath:goldenbridge-dao.xml"/>
	<import resource="classpath:goldenbridge-service.xml"/>
	<import resource="classpath:goldenbridge-cxf.xml"/>
    <!--<import resource="classpath:goldenbridge-shiro.xml"/>
	 <import resource="classpath:goldenbridge-cxf.xml"/> -->
	
	
</beans>

3.myabits-generator配置

mybatis-generator配置檔案如下

主要配置資料來源的地址,以及生成的JavaBean、Mapper介面、以及Mapper.xml檔案位置所在路徑

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE generatorConfiguration
   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
	<context id="oracleTables">
		<commentGenerator>
			<property name="suppressDate" value="true" />
			<property name="suppressAllComments" value="true" />
			<property name="mergeable" value="true"></property>
		</commentGenerator>
		<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
			connectionURL="jdbc:oracle:thin:@192.168.2.254:1521:orcl" userId="certific"
			password="certific">

		</jdbcConnection>
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<javaModelGenerator targetPackage="com.goldenbridge.certificicsystem.model"
			targetProject="src/main/java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.goldenbridge.certificicsystem.mapper"
			targetProject="src/main/java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<table tableName="NEWS_INFO" domainObjectName="NewsInfo"></table>
	</context>
</generatorConfiguration>

myabits-generaotr執行主要依賴maven的org.mybatis.generator外掛,pom.xml的外掛配置程式碼如下!

<plugins>
    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
         <configuration>
            <verbose>true</verbose>
            <overwrite>true</overwrite>
        </configuration>
        <dependencies>
        	<dependency>
		    <groupId>org.mybatis.generator</groupId>
		    <artifactId>mybatis-generator-core</artifactId>
		    <version>1.3.2</version>
		</dependency>
		<dependency>
	    <groupId>com.oracle</groupId>
	    <artifactId>classes12</artifactId>
	    <version>10.2.0.2.0</version>
	</dependency>
		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
		    <groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
		    <version>1.2.17</version>
		</dependency>
  </dependencies>
    </plugin>

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>1.7</source>
        <target>1.7</target>
        <encoding>UTF-8</encoding>
      </configuration>
    </plugin>
    </plugins>

執行方式則為:mybatis-generate:generator

4. mybatis配置

這個沒什麼好說的,主要是將mybatis-generator生成的Mapper.xml匯入進去,以及配置PageHelper分頁資訊,程式碼如下

<?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>
	    <settings>
	        
	        <setting name="logImpl" value="STDOUT_LOGGING" />
	    </settings>
		<plugins>
				 <!-- com.github.pagehelper為PageHelper類所在包名 -->
		    <plugin interceptor="com.github.pagehelper.PageHelper">
		        <property name="dialect" value="oracle"/>
		        <!-- 該引數預設為false -->
		        <!-- 設定為true時,會將RowBounds第一個引數offset當成pageNum頁碼使用 -->
		        <!-- 和startPage中的pageNum效果一樣-->
		        <property name="offsetAsPageNum" value="true"/>
		        <!-- 該引數預設為false -->
		        <!-- 設定為true時,使用RowBounds分頁會進行count查詢 -->
		        <property name="rowBoundsWithCount" value="true"/>
		        <!-- 設定為true時,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結果 -->
		        <!-- (相當於沒有執行分頁查詢,但是返回結果仍然是Page型別)-->
		        <property name="pageSizeZero" value="true"/>
		        <!-- 3.3.0版本可用 - 分頁引數合理化,預設false禁用 -->
		        <!-- 啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最後一頁 -->
		        <!-- 禁用合理化時,如果pageNum<1或pageNum>pages會返回空資料 -->
		        <property name="reasonable" value="true"/>
		        <!-- 3.5.0版本可用 - 為了支援startPage(Object params)方法 -->
		        <!-- 增加了一個`params`引數來配置引數對映,用於從Map或ServletRequest中取值 -->
		        <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置對映的用預設值 -->
		        <property name="params" value="pageNum=start;pageSize=limit;pageSizeZero=zero;reasonable=heli;count=contsql"/>
		    </plugin>
	</plugins>
	<!-- 實體介面對映資源 -->
	<!--
		說明:如果xxMapper.xml配置檔案放在和xxMapper.java統一目錄下,mappers也可以省略,因為org.mybatis.spring.mapper.MapperFactoryBean預設會去查詢與xxMapper.java相同目錄和名稱的xxMapper.xml
	-->
	
	<mappers>
	
		<mapper resource="mapper/NewsInfoMapper.xml"/>

	</mappers>

</configuration>  

5.SpringMVC配置

springmvc配置不多說,檔案如下

<?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: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">
      
	 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
	 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
	    <property name="messageConverters">  
	        <list>  
	            <bean class="com.goldenbridge.certificicsystem.utils.UTF8StringHttpMessageConverter" />  
	        </list>  
	    </property> 
	    <property name="webBindingInitializer">
			<bean
				class="com.goldenbridge.certificicsystem.utils.MyWebBindingInitializer" />
		</property> 
	</bean>
	 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	 	<property name="defaultEncoding" value="utf-8"></property>
	 	<property name="maxUploadSize" value="102857600"></property>
	 </bean>
	 <context:component-scan base-package="com.goldenbridge.certificicsystem.controller" />
</beans>

web.xml配置如下

其中SimpleCORSFilter主要是為了允許跨域訪問而配置的

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
      <welcome-file>pages/index.html</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Spring 的監聽器可以通過這個上下文引數來獲取beans.xml的位置 -->

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>
  
  
  <servlet>
  		<servlet-name>certificicsystem</servlet-name>
  		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  		<servlet-name>certificicsystem</servlet-name>
  		<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <filter>  
    <filter-name>encodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
      <param-name>encoding</param-name>  
      <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
      <param-name>forceEncoding</param-name>  
      <param-value>true</param-value>  
    </init-param>  
  </filter>  
  <filter-mapping>  
    <filter-name>encodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
  </filter-mapping>
  
  <filter> 
  	<filter-name>DruidWebStatFilter</filter-name>  
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>  
      </filter>  
      <filter-mapping>  
        <filter-name>DruidWebStatFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
      </filter-mapping>      
	 <servlet>  
        <servlet-name>DruidStatView</servlet-name>  
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>DruidStatView</servlet-name>  
        <url-pattern>/druid/*</url-pattern>  
    </servlet-mapping>
    
    
    <filter>  
     <filter-name>SimpleCORSFilter</filter-name>  
     <filter-class>com.goldenbridge.certificicsystem.utils.SimpleCORSFilter</filter-class>  
  </filter>  
  <filter-mapping>  
      <filter-name>SimpleCORSFilter</filter-name>  
      <url-pattern>/*</url-pattern>  
  </filter-mapping>
    
</web-app>


以上核心配置檔案就到這裡結束了

6.底層核心程式碼

為了是開發更加的簡單,不用再去為每個Bean物件去寫一套底層的crud的dao層程式碼,我通過泛型與反射技術編寫了一套通用的底層程式碼BaseDao,主要封裝了crud等方法,之後通過類繼承的方式整合BaseDao則就可以自動實現,程式碼如下

BaseDao.java

package com.goldenbridge.certificicsystem.dao;

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

import org.apache.ibatis.session.SqlSession;

import com.goldenbridge.certificicsystem.model.PageBean;

public interface BaseDao<T,S> {
	
	PageBean findByExample(PageBean<T> pagebean,S arg0);
	
	T getBeanById(String id);
	
	T getByName(String name);
	
	T getByExample(S arg0);
	
	void insert(T t);
	
	void update(T t);
	
	void delete(String id);
	
	void deleteByExample(S s);
	
	List<T> findAll();
	
	List<T> findListByExample(S s);
	
	SqlSession getSession();
	
	int count(S s);
	
	
	String getSequencesByName(String name);

	Map<String, Object> executeSql(String sql,String value[]);
}

BaseDaoImpl.java
package com.goldenbridge.certificicsystem.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils;

import com.github.pagehelper.PageHelper;
import com.goldenbridge.certificicsystem.dao.BaseDao;
import com.goldenbridge.certificicsystem.model.PageBean;

public class BaseDaoImpl<T,S> extends BeanFactoryAnnotationUtils implements BaseDao<T, S>{
	
	@Resource SqlSessionTemplate sqlSession;
	
	protected Class clazz_t,clazz_s;
	protected Object object;
	protected T t;
	protected S s;
	protected Method method;
	protected Class mapperclass;
	
	public BaseDaoImpl(){
		ParameterizedType pt = null;
		try {
			pt =  (ParameterizedType) this.getClass().getGenericSuperclass();
		} catch (Exception e1) {
			pt =  (ParameterizedType) this.getClass().getSuperclass().getGenericSuperclass();
		}
		
		clazz_t = (Class) pt.getActualTypeArguments()[0];
		clazz_s = (Class) pt.getActualTypeArguments()[1];
		//String mapperClassName = clazz_t.getName()+"Mapper";
		String classname = clazz_t.getName();
		classname = classname.substring(0,classname.lastIndexOf("."));
		classname = classname.substring(0,classname.lastIndexOf(".")+1);
		String mapperClassName = classname +"mapper."+ clazz_t.getSimpleName() + "Mapper";
		try {
			mapperclass = Class.forName(mapperClassName);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public PageBean<T> findByExample(PageBean<T> pagebean,S arg0){//根據條件查詢集合分頁
			List<T> list = null;
			try {
				object = sqlSession.getMapper(mapperclass);
				method = object.getClass().getDeclaredMethod("selectByExample", clazz_s);
				PageHelper.startPage(pagebean.getPagenow(), pagebean.getPagesize());
				list = (List<T>) method.invoke(object, arg0);
				pagebean.setList(list);
				method = object.getClass().getDeclaredMethod("countByExample", clazz_s);
				Integer count = (Integer) method.invoke(object, arg0);
				pagebean.setCount(count);
				object = null;
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				method = null;
			}
			return pagebean;
	}
	
	public T getBeanById(String id){//通過id查詢物件
		T t = null;
			try {
				object = sqlSession.getMapper(mapperclass);
				method = object.getClass().getDeclaredMethod("selectByPrimaryKey", id.getClass());
				t = (T) method.invoke(object, id);
				object = null;
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				method = null;
			}
			
		return t;
		
	}
	
	
	
	public int count(S s){//插入方法
		int resutl = 0;
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("countByExample", s.getClass()); //通過反射獲取方法物件
			resutl = (int) method.invoke(object, s); //執行方法
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		
		return resutl;
	}
	
	public void insert(T t){//插入方法
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("insert", t.getClass()); //通過反射獲取方法物件
			method.invoke(object, t); //執行方法
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
	}
	
	public void update(T t){
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("updateByPrimaryKeySelective", clazz_t);//getDeclaredMethod()獲取類的方法例項
			method.invoke(object, t);//invoke執行這個方法
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		
		
	}
	
	public void delete(String id){
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("deleteByPrimaryKey", id.getClass());
			method.invoke(object, id);
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
	}

/*
	public void setBeanFactory(BeanFactory arg0) throws BeansException { //獲取spring容器
		this.beanFactory = arg0;
		
		ParameterizedType pt =  (ParameterizedType) this.getClass().getSuperclass().getGenericSuperclass();
		clazz_t = (Class) pt.getActualTypeArguments()[0];
		clazz_s = (Class) pt.getActualTypeArguments()[1];
		System.out.println(clazz_t+":"+clazz_s);
		try {
			t = (T) clazz_t.newInstance();
			s = (S) clazz_s.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		String className = clazz_t.getSimpleName();
		String indexstart = className.substring(0, 1);
		className = indexstart.toLowerCase()+className.substring(1);
		object = beanFactory.getBean(className+"Mapper");
		
	}
*/
	public List<T> findAll() {
		List<T> list = null;
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("selectByExample", clazz_s);
			
			list = (List<T>) method.invoke(object,clazz_s.newInstance());
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		return list;
	}

	public T getByName(String name) {
		T t = null;
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("selectByExample", clazz_s);
			Object S_Example = clazz_s.newInstance();
			Method s_method = clazz_s.getDeclaredMethod("createCriteria");
			Object Criteria = s_method.invoke(S_Example);
			Method[] methods = Criteria.getClass().getMethods();
			Method EqualToName = Criteria.getClass().getMethod("andNameEqualTo", String.class);
			
			EqualToName.invoke(Criteria, name);
			List<T> list = (List<T>) method.invoke(object, S_Example);
			if(list != null && list.size() > 0){
				t = list.get(0);
			}
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		return t;
	}
	
	public List<T> findListByExample(S arg0) {//根據條件查詢集合
		List<T> list = null;
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("selectByExample", clazz_s);
			list = (List<T>) method.invoke(object, arg0);
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		return list;
	}
	
	
	@Override
	public void deleteByExample(S s) {
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("deleteByExample", clazz_s);
			method.invoke(object, s);
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		
	}

	@Override
	public T getByExample(S arg0) {
		T result = null;
		List<T> list = null;
		try {
			object = sqlSession.getMapper(mapperclass);
			method = object.getClass().getDeclaredMethod("selectByExample", clazz_s);
			list = (List<T>) method.invoke(object, arg0);
			if(list !=null && list.size() > 0)
				result = list.get(0);
			object = null;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			method = null;
		}
		return result;
	}
	
	@Override
	public SqlSession getSession() {
		return sqlSession;
	}

	@Override
	public String getSequencesByName(String name) {
		String result = sqlSession.selectOne("com.goldenbridge.certificicsystem.mapper.BaseUtils.getSequencesByName", name);
		/*Connection conn = sqlSession.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select "+name+".NEXTVAL FROM DUAL";
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()){
				result = rs.getString("NEXTVAL");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs != null){
					rs.close();
					rs = null;
				}
				if(ps != null){
					ps.close();
					ps = null;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		
		return result;
	}
	
	@Override
	public Map<String, Object> executeSql(String sql,String values[]){
		Map<String, Object> result=new HashMap<String, Object>();
		Connection conn = sqlSession.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()){
				for(String value:values){
					if(StringUtils.isNotBlank(rs.getString(value.toUpperCase()))){
						result.put(value, rs.getString(value.toUpperCase()));
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs != null){
					rs.close();
					rs = null;
				}
				if(ps != null){
					ps.close();
					ps = null;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
}

如果需要建立Bean的Dao層程式碼,則只需要整合BaseDao就行了,裡面的泛型物件文JavaBean與JavaBeanExample,這兩個物件都是mybatis-generator生成的,不用手動建立,程式碼如下!

Dao層

NewsInfoDao.java

package com.goldenbridge.certificicsystem.dao;

import com.goldenbridge.certificicsystem.model.NewsInfo;
import com.goldenbridge.certificicsystem.model.NewsInfoExample;

public interface NewsInfoDao extends BaseDao<NewsInfo, NewsInfoExample>{

}
NewsInfoDaoImpl.java
package com.goldenbridge.certificicsystem.dao.impl;

import com.goldenbridge.certificicsystem.dao.NewsInfoDao;
import com.goldenbridge.certificicsystem.model.NewsInfo;
import com.goldenbridge.certificicsystem.model.NewsInfoExample;

public class NewsInfoDaoImpl extends BaseDaoImpl<NewsInfo, NewsInfoExample> implements NewsInfoDao{

}

Service層

在Service層一樣,這裡只需要基層Dao層就行了,程式碼就不貼上了!

Controller層

該層與平時使用SpringMVC一樣沒什麼其他區別,程式碼型別如下!

package com.goldenbridge.certificicsystem.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goldenbridge.certificicsystem.model.CgbRole;
import com.goldenbridge.certificicsystem.model.CgbRoleExample;
import com.goldenbridge.certificicsystem.model.CgbUser;
import com.goldenbridge.certificicsystem.model.PageBean;
import com.goldenbridge.certificicsystem.service.IAuthorityService;
import com.goldenbridge.certificicsystem.service.ICgbRoleService;
import com.goldenbridge.certificicsystem.utils.JSONTools;






import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value="/role")
public class RoleController {

	
	@Resource IAuthorityService authorityService;
	@Resource ICgbRoleService cgbRoleService;
	
	@RequestMapping(value="/menulist")
	public @ResponseBody String getMenuList() {
		JSONArray object = cgbRoleService.getAuthorityList(null);
		return object.toString();
	}
	
	
	/**
	 * @param sysRole
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public @ResponseBody String add(@ModelAttribute CgbRole sysRole,HttpServletRequest request){
		try {
			CgbRoleExample cgbRoleExample = new CgbRoleExample();
			cgbRoleExample.createCriteria().andRolenameEqualTo(sysRole.getRolename());
			CgbRole cgbRole=cgbRoleService.getByExample(cgbRoleExample);
			if(cgbRole !=null ){
				return JSONTools.formatJSONObjectToString(0, "角色名稱專案", null);
			}
			cgbRoleService.addRole(sysRole, request);
			return JSONTools.formatJSONObjectToString(1, "操作成功!", null);
		} catch (Exception e) {
			e.printStackTrace();
			return JSONTools.formatJSONObjectToString(0, "操作異常", null);
		}
	}
	
	@RequestMapping(value="/search",method=RequestMethod.POST)
	public @ResponseBody String Search(int pagenow,HttpSession session){
		
		try {
			PageBean<CgbRole> pagebean = new PageBean<CgbRole>();
			pagebean.setPagenow(pagenow);
			CgbUser sysUser = (CgbUser) session.getAttribute("sysUser");
			cgbRoleService.search(pagebean,sysUser);
			return JSONTools.formatJSONObjectToString(1, "成功", pagebean);
		} catch (Exception e) {
			e.printStackTrace();
			return JSONTools.formatJSONObjectToString(0, "失敗", null);
		}
	}
	
	@RequestMapping(value="/authority",method=RequestMethod.GET)
	public @ResponseBody String authority(HttpSession session){
		CgbUser sysUser = (CgbUser) session.getAttribute("sysUser");
		JSONObject jsonObject = cgbRoleService.getObjectAuthorityList(sysUser);
		return jsonObject.toString();
	}
	
	/**
	 * pengweikang 20161028 跳轉到修改頁面
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/{id}/update",method=RequestMethod.GET)
	public String toupdate(@PathVariable String id){
		return "role/update";
	}


程式碼差不多就這麼多了,小夥伴趕緊動手試試吧!