1. 程式人生 > >SpringMVC4+Spring4+Hibernate4框架整合

SpringMVC4+Spring4+Hibernate4框架整合


                            SpringMVC4 + Spring4 + Hibernate4 框架搭建中。。。


作者:vashon

時間:2016-09-03


前言


現在很多企業流行用mybatis + spring + springmvc框架,但是mybatis或ibatis編寫SQL較麻煩且對於資料庫的移植性不好,你覺得呢?如果你也感覺mybatis或ibatis編寫SQL較麻煩,那SpringMVC+Spring+Hibernate的整合適合
你,如果你覺得Strut2沒有SpringMVC好用,存在漏洞,執行效率不高容易爆記憶體,那SpringMVC+Spring+Hibernate整合適合你,看好SpringMVC+Spring+Hibernate的搭配,此SSH非彼SSH。

總體來說:Hibernate入門門檻比Mybatis高,但個人還是偏向於Hibernate,用慣了Hibernate的都感覺Hibernate才是標準的ORM框架,而且資料庫可移植性好(換資料庫只需修改方言和資料庫配置即可);Mybatis這種半自動化的雖然靈活,可優化SQL,但是對於資料庫的移植性來說就差了,而對於Hiberante只要控制的好,功能更強大。


選擇SpringMVC4+Spring4+Hibernate4的原因


仔細分析過Struts2與SpringMVCMybatis與Hibernate的優勢與劣勢之後,總想搭建出一套在表現出、持久層中整體佔優勢的框架。於是就決定了SpringMVC+Spring+Hibernate框架的整合搭建,為了考慮到系統以後會用到新框架的一些特性,所有就決定搭建SpringMVC4+Spring4+Hibernate4的框架。


目標:有點追求,搭建出一套屬於自己的框架,慢慢維護這套框架,深入研究這套框架的新特性,封裝這套框架,讓它變得越來越好。。。也讓自己擁有“走在架構師路上”的感覺。



準備工作


hibernate4下載地址  http://hibernate.org/orm/

SpringMVC  官網:http://projects.spring.io/spring-framework
下載地址:http://repo.spring.io/release/org/springframework/spring/4.2.2.RELEASE/


僅下載:

spring-framework-4.2.2.RELEASE-dist.zip   
spring-framework-4.2.2.RELEASE-docs.zip 
spring-framework-4.2.2.RELEASE-schema.zip 


後續將加入Spring-Security的安全訪問控制解決方案的安全框架

下載地址:http://repo.spring.io/libs-release-local/org/springframework/security/spring-security/

Spring Security開發手冊:http://docs.spring.io/spring-security/site/docs/4.1.0.RELEASE/reference/htmlsingle/#ns-minimal


搭建需要準備jar(目前基礎版本,後面會隨著spring security應用以及基類封裝jar會增多):


                                                   



搭建環境的配置


一、web.xml中的配置檔案:


<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>nssh</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- 配置Spring IOC 容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 配置SpringMVC 的 DispatcherServlet 控制器 -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置DispatcherServlet的一個初始化引數:配置SpringMVC配置檔案的位置名稱 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

	<!-- 配置編碼方式過濾器,注意一點:要配置在所有過濾器的前面 -->
	<filter>
		<filter-name>characterEncodingFilter</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>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 為了使用SpringMVC框架實現REST風格,需要配置  HiddenHttpMethodFilter-->
	<filter>
		<filter-name>hiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>hiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app></span><span style="font-size: 18px;">
</span>



二、Spring的applicationContext.xml配置檔案:


<?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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-lazy-init="true">

	<!-- 配置自動掃描的包 --> 
	<context:component-scan base-package="com.ywx" use-default-filters="false">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>
	
	<!-- 配置資料來源 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 配置DataSource -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
	</bean>
	
	<!-- 配置SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置資料來源屬性 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配置掃描的實體包(pojo) -->
		<property name="namingStrategy">
			<bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>
		</property>
		<property name="packagesToScan" value="com.ywx.entity"></property>
		
		<!-- 配置Hibernate 的常用屬性 -->
		<property name="hibernateProperties">
			<props>
			<!-- 資料庫的方言 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>
	
	<!-- 配置Hibernate 的事物管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
</beans>


三、SpringMVC中springmvc.xml檔案:


<span style="font-size:14px;"><?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.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="com.ywx" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>

	<!-- 配置檢視解析器:如何把handler方法返回值解析為實際的物理檢視 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"></property>
		<property name="suffix" value=".jsp"></property> 
	</bean>

	<!-- 配置靜態資源:default-servlet-handler將在SpringMVC上下文中定義DefaultServletHttpRequestHandler, 
		它會對進入DispatcherServlet的請求進行帥選,如果發現是沒有經過對映的請求,就將該請求交由WEB應用伺服器預設的 Servlet處理。如果不是靜態資源的請求,才由DispatcherServlet繼續處理。 -->
	<mvc:default-servlet-handler />
	<!-- 配置開啟註解 -->
	<mvc:annotation-driven/>

</beans>
</span>



四、資料庫db.properties檔案:


jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mysql

#jdbc.user=ssh
#jdbc.password=ssh
#jdbc.driverClass=oracle.jdbc.driver.OracleDriver
#jdbc.jdbcUrl=jdbc:oracle:thin:@localhost:1521:ORCL



測試環節


一、編寫測試類:



二、測試結果:






控制檯出現的紅色部分是因為log日子沒有處理


log日子處理:


匯入log4j.jar

然後修改log4j.properties檔案如下(日子輸出等級根據需求而設定):

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
log4j.logger.com.ywx=debug



日誌處理為debug後的輸出為:





現在SpirngMVC+Spring+Hibernate的框架整合完成,目前還是一個空殼,其底層的DAO基類還在封裝中。。。



基礎程式碼封裝遇到的問題

1、Spring4+Hibernate4整合後SessionFactory、Session及log的問題

2、mappedBy與@JoinColumn共存問題

3、Hibernate4主鍵生成策略問題



框架整合搭建完成,底層對Hibernate Dao的原生API封裝完成,還加了一套字典、使用者許可權後的jar:

                          


本套架構借鑑了公司一個大型專案底層架構的同時,在其基礎上擴充套件了dao和service層的多型,解決了部分單繼承的侷限。整體來說架構的健壯性增強了,也提供了對事務一致性的控制,但其複雜度也增加了。總的來說,這套後臺的架構我甚是滿意 ^ _ ^,後續會提供原始碼。



整合Spring-Security安全訪問控制框架



1、下載Spring-Security:http://repo.spring.io/libs-release-local/org/springframework/security/spring-security/



下載第一個,裡面包含了所有的檔案。




原始碼請點選:原始碼下載


框架圖: