程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Maven 搭建SpringMVC+Hibernate項目詳解

Maven 搭建SpringMVC+Hibernate項目詳解

編輯:關於JAVA

Maven 搭建SpringMVC+Hibernate項目詳解。本站提示廣大學習愛好者:(Maven 搭建SpringMVC+Hibernate項目詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Maven 搭建SpringMVC+Hibernate項目詳解正文


媒介

     明天溫習一下SpringMVC+Hibernate的搭建,原來想著將Spring-Security權限掌握框架也映入個中的,然則發明內容太多了,Spring-Security的就留鄙人一篇吧,這篇重要搭建SpringMVC4.1.4和Hibernate4.3.8,之前也打了很多多少SpringMVC的,這部門曾經異常的熟習了,究竟業開辟過一年多SpringMVC的,此次耐久層采取Hibernate,數據源采取c3p0,數據庫暫采取MySQL,重要是想溫習一下Hibernate。搭建SpringMVC+Hibernate的框架的思緒以下:

     1、設計數據庫:設計好表構造,最好相符3NF,采取Hibernate tools將設計好的表主動生成對應的實體entity。 

     1、創立Maven項目,按需映入Maven包依附。

     2、搭建Spring:設置裝備擺設Spring對控件層Bean的注入。

     3、搭建Hibernate:設置裝備擺設數據源,設置裝備擺設SessionFactory,設置裝備擺設事務,和二級緩存ehcache的設置裝備擺設。

     4、測試Spring+Hibernate的框架搭建,寫單位測試JUnit,測試事務設置裝備擺設等。

     5、映入SpringMVC:設置裝備擺設SpringMVC設置裝備擺設信息。

     6、設置裝備擺設web.xml容器

     7、測試三個框架的整合:Maven編譯打包安排辦事器,測試。

1、數據庫設計

       設計一個權限、腳色、用戶的表。天然假如一個用戶可以有多個腳色,一個腳色多個用戶所具有;一個腳色具有多個權限,一個權限對應多個腳色。所以依照數據庫表構造設計,相符3NF的話我們須要5張表停止存在。表的詳細信息就不列出了(可以下在源碼,外面還稀有據庫),表關系以下:


      這外面ID才用到是java的UUID(36位)

2、創立Maven項目,編寫pom.xml文件

      創立一個Maven的webapp項目,編寫pom.xml文件,引入所需的包依附,我這裡就將所需的全體的映入了。

       

      pom.xml文件內容以下:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.andy.sh</groupId>
 <artifactId>springmvc_hibernate_demo</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>

 <name>springmvc_hibernate_demo Maven Webapp</name>
 <url>http://maven.apache.org</url>

 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <spring.version>4.1.4.RELEASE</spring.version>
 <hibernate.version>4.3.8.Final</hibernate.version>
 <jackson.version>2.5.0</jackson.version>
 </properties>

 <dependencies>

 <!-- junit -->
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.12</version>
 <scope>test</scope>
 </dependency>

 <!-- spring -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-tx</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>${spring.version}</version>
 <scope>test</scope>
 </dependency>

 <!-- 應用SpringMVC需設置裝備擺設 -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <!-- 關系型數據庫整應時需設置裝備擺設 如hibernate jpa等 -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-orm</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <!-- hibernate -->
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>${hibernate.version}</version>
 </dependency>

 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-ehcache</artifactId>
 <version>${hibernate.version}</version>
 </dependency>

 <!-- 二級緩存ehcache -->
 <dependency>
 <groupId>net.sf.ehcache</groupId>
 <artifactId>ehcache</artifactId>
 <version>2.9.0</version>
 </dependency>

 <!-- log4j -->
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
 </dependency>

 <!-- mysql銜接 -->
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.34</version>
 </dependency>

 <!-- c3p0數據源 -->
 <dependency>
 <groupId>com.mchange</groupId>
 <artifactId>c3p0</artifactId>
 <version>0.9.5-pre10</version>
 </dependency>

 <!-- json -->
 <dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>fastjson</artifactId>
 <version>1.2.3</version>
 </dependency>

 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-annotations</artifactId>
 <version>${jackson.version}</version>
 </dependency>

 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>${jackson.version}</version>
 </dependency>

 <dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>${jackson.version}</version>
 </dependency>

 <!-- aop -->
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjweaver</artifactId>
 <version>1.8.4</version>
 </dependency>

 <!-- servlet -->
 <dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>servlet-api</artifactId>
 <version>3.0-alpha-1</version>
 <scope>provided</scope>
 </dependency>

 <dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>jstl</artifactId>
 <version>1.2</version>
 </dependency>

 </dependencies>

 <build>
 <finalName>springmvc_hibernate_demo</finalName>

 <plugins>
 <!-- Run the JUnit unit tests in an isolated classloader -->
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>2.4.2</version>
 <configuration>
 <skipTests>true</skipTests>
 </configuration>

 </plugin>

 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-war-plugin</artifactId>
 <version>2.3</version>
 <configuration>
 <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
 </configuration>
 </plugin>

 <!-- generate java doc -->
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-javadoc-plugin</artifactId>
 <version>2.9.1</version>
 <configuration>
 <javadocDirectory>target/javadoc</javadocDirectory>
 <reportOutputDirectory>target/javadoc</reportOutputDirectory>
 <charset>UTF-8</charset>
 <encoding>UTF-8</encoding>
 <docencoding>UTF-8</docencoding>
 <show>private</show>
 </configuration>
 </plugin>

 <!-- 安排至本機 -->
 <plugin>
 <groupId>org.codehaus.cargo</groupId>
 <artifactId>cargo-maven2-plugin</artifactId>
 <version>1.0</version>
 <configuration>
 <container>
 <containerId>tomcat6x</containerId>
 <home>D:\WebServer\apache-tomcat-6.0.39</home>
 </container>
 <configuration>
 <type>existing</type>
 <home>D:\WebServer\apache-tomcat-6.0.39</home>
 </configuration>
 </configuration>
 </plugin>
 </plugins>

 </build>
</project>

3、引入Spring設置裝備擺設

    編寫設置裝備擺設文件,設置裝備擺設文件放在src/main/resources資本目次下(下同)。

   項目所需的設置裝備擺設信息config.properties

 

#application configs

#jdbc c3p0 config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/work?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 12345

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path = ehcache.xml

3.1、spring設置裝備擺設

spring.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:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.1.xsd">
 <!-- 加載設置裝備擺設文件 -->
 
 <context:property-placeholder location="classpath:config.properties"/>
 <!-- 掃描service主動注入為bean -->
 <context:component-scan base-package="org.andy.work.service.impl,org.andy.work.dao.impl" />

</beans>

下面spring設置裝備擺設了對應包下組件bean主動注入治理,我們須要將dao,service的完成類交由spring治理,如(@Repository,@Service)。

3.2、引入日記文件設置裝備擺設Log4j

 log4j.properties的設置裝備擺設文件以下:

### set log levels ###
log4j.rootLogger = INFO , C , D , E 

### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/springmvc_hibernate_demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/springmvc_hibernate_demo_error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [sspringmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n



4、Hibernate設置裝備擺設

      Hibernate的設置裝備擺設重要包含:設置裝備擺設數據源c3p0,設置裝備擺設SessionFactory,設置裝備擺設事務治理器,設置裝備擺設事務治理,其spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
 http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

 <!-- 設置裝備擺設數據源 c3p0 -->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
 destroy-method="close">
 <property name="driverClass" value="${jdbc.driver}" />
 <property name="jdbcUrl" value="${jdbc.url}" />
 <property name="user" value="${jdbc.username}" />
 <property name="password" value="${jdbc.password}" />

 <!-- 要求超不時間 -->
 <property name="checkoutTimeout" value="30000" />
 <!-- 每60秒檢討一切銜接池中的余暇銜接。默許值: 0,不檢討 -->
 <property name="idleConnectionTestPeriod" value="30" />
 <!-- 銜接數據庫銜接池最年夜余暇時光 -->
 <property name="maxIdleTime" value="30" />
 <!-- 銜接池初始化銜接數 -->
 <property name="initialPoolSize" value="5" />
 <property name="minPoolSize" value="5" />
 <property name="maxPoolSize" value="20" />
 <!--當銜接池中的銜接耗盡的時刻c3p0一次同時獲得的銜接數。默許值: 3 -->
 <property name="acquireIncrement" value="5" />
 </bean>

 <!-- 設置裝備擺設hibernate的SessionFactory -->
 <bean id="sessionFactory"
 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 <!-- 注入數據源 相干信息看源碼 -->
 <property name="dataSource" ref="dataSource" />
 <!-- hibernate設置裝備擺設信息 -->
 <property name="hibernateProperties">
 <props>
 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>

 <!-- 開啟二級緩存 ehcache -->
 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
 <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
 <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
 </prop>
 </props>
 </property>
 <!-- 掃描hibernate注解設置裝備擺設的entity -->
 <property name="packagesToScan" value="org.andy.work.entity" />
 </bean>

 <!-- 設置裝備擺設事務治理器 -->
 <bean id="transactionManager"
 class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <!-- 設置裝備擺設事務加強處置Bean,指定事務治理器 -->
 <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
 <!-- 設置裝備擺設具體事務處置語義 -->
 <tx:attributes>
 <tx:method name="insert*" propagation="REQUIRED" />
 <tx:method name="update*" propagation="REQUIRED" />
 <tx:method name="delete*" propagation="REQUIRED" />

 <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
 <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
 <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
 <tx:method name="load*" propagation="SUPPORTS" read-only="true" />

 <!-- 其他采取默許事務方法 -->
 <tx:method name="*" />

 </tx:attributes>
 </tx:advice>

 <!-- Spring aop事務治理 -->
 <aop:config>
 <!-- 設置裝備擺設切入點 -->
 <aop:pointcut id="transactionPointcut"
 expression="execution(* org.andy.work.service..*Impl.*(..))" />
 <!-- 指定在txAdvice切入點運用txAdvice事務加強處置 -->
 <aop:advisor pointcut-ref="transactionPointcut"
 advice-ref="transactionAdvice" />
 </aop:config>

</beans>

 下面設置裝備擺設了二級緩存,ehcache,相干的詳細信息檢查上一篇Hibernate二級緩存和ehcache的搭建設置裝備擺設,上面是二級緩存的設置裝備擺設。

4.1、ehcache.xml的設置裝備擺設      

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 <diskStore path="D:/ehcache" />
 <!-- DefaultCache setting. -->
 <defaultCache
 maxElementsInMemory="1000"
 eternal="false"
 timeToIdleSeconds="120"
 timeToLiveSeconds="120"
 maxElementsOnDisk="1000000"
 overflowToDisk="true" 
 memoryStoreEvictionPolicy="LRU">
 
 </defaultCache>

 <!-- Special objects setting. -->

 <cache 
 name="org.andy.work.entity.AcctUser"
 maxElementsInMemory="2"
 memoryStoreEvictionPolicy="LRU" 
 eternal="true" 
 diskPersistent="false"
 overflowToDisk="false" 
 maxElementsOnDisk="1000000" /> 



</ehcache>

   下面Hibernate二級緩存ehcache寄存磁盤是D:/ehcache

5、生成營業entity實體

      設計好數據表後,Hibernate的實體有對象Hibernate tools主動生成,Eclipse須要裝置Hibernate tools插件(我在線裝置過幾回都不勝利,推舉應用links離線裝置,附錄將引見),所以不須要手工的書寫,上面就貼一個用戶信息的實體,AcctUser.java

 

package org.andy.work.entity;

// Generated 2015-2-3 10:43:00 by Hibernate Tools 4.0.0

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * AcctUser generated by hbm2java
 */
@Entity
@Table(name = "acct_user", catalog = "work")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AcctUser implements java.io.Serializable {

 /**
 * 
 */
 private static final long serialVersionUID = 6980093847795726310L;
 private String id;
 private String nickName;
 private String telephone;
 private Date registerTime;
 private Set<AcctRole> acctRoles = new HashSet<AcctRole>(0);

 public AcctUser() {

 }

 public AcctUser(String id, String nickName) {
 this.id = id;
 this.nickName = nickName;
 }

 public AcctUser(String id, String nickName, String telephone,
 Date registerTime, Set<AcctRole> acctRoles) {
 this.id = id;
 this.nickName = nickName;
 this.telephone = telephone;
 this.registerTime = registerTime;
 this.acctRoles = acctRoles;
 }

 @Id
 @Column(name = "id", unique = true, nullable = false, length = 36)
 public String getId() {
 return this.id;
 }

 public void setId(String id) {
 this.id = id;
 }

 @Column(name = "nick_name", nullable = false)
 public String getNickName() {
 return this.nickName;
 }

 public void setNickName(String nickName) {
 this.nickName = nickName;
 }

 @Column(name = "telephone")
 public String getTelephone() {
 return this.telephone;
 }

 public void setTelephone(String telephone) {
 this.telephone = telephone;
 }

 @Temporal(TemporalType.TIMESTAMP)
 @Column(name = "register_time", length = 19)
 public Date getRegisterTime() {
 return this.registerTime;
 }

 public void setRegisterTime(Date registerTime) {
 this.registerTime = registerTime;
 }

 @JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"})
 @ManyToMany(fetch = FetchType.LAZY)
 @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
 @JoinTable(name = "acct_user_role", catalog = "work", joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
 public Set<AcctRole> getAcctRoles() {
 return this.acctRoles;
 }

 public void setAcctRoles(Set<AcctRole> acctRoles) {
 this.acctRoles = acctRoles;
 }

}

下面有幾個須要留意的:

     下面年夜多半都是Hibernate tools主動生成的,然則有幾個須要手動添加:

              1、假如這個實體應用二級緩存的話,須要添加@cache注解;

              2、假如該實體外面還有聚集元素(set, map,list),假如實體要采取二級緩存,那末這些聚集元素必需也添加@cache注解。

              3、@JsonIgnoreProperties注解是為了避免SpringMVC在json前往時發生輪回輸入應用,假如不設置裝備擺設的話就會湧現json逝世輪回(還有多對多,一對多的屬性時)。

             4、@JsonIgnore這個是在轉換成json是疏忽該屬性,而@JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"})則是疏忽acctRoles外面的acctUsers和acctAuthorites屬性。

6、創立Dao層

6.1Dao接口

              Dao層和Service層我們確定采取的是面相接口編程的思惟,所以,我們先界說一個通用的Dao接口,GenericDao.java

 

package org.andy.work.dao;

import java.io.Serializable;
import java.util.List;

/**
 * 創立時光:2015-2-6 下晝2:26:42
 * 
 * @author andy
 * @version 2.2
 * 
 * Dao通用接口
 */

interface GenericDao<T, PK extends Serializable> {
 
 T load(PK id);
 
 T get(PK id);
 
 List<T> findAll();
 
 void persist(T entity);
 
 PK save(T entity);
 
 void saveOrUpdate(T entity);
 
 void delete(PK id);
 
 void flush();
}

            在界說詳細的UserDao.java接口        

package org.andy.work.dao;

import org.andy.work.entity.AcctUser;

/**
 * 創立時光:2015-2-6 下晝2:43:50
 * 
 * @author andy
 * @version 2.2
 * 
 * 用戶Dao接口
 */

public interface UserDao extends GenericDao<AcctUser, String> {

}

6.2、Dao層完成類

    我們須要將Dao層的完成類注入為bean,所以須要添加@Repository注解,UserDaoImpl以下:

package org.andy.work.dao.impl;

import java.util.List;

import org.andy.work.dao.UserDao;
import org.andy.work.entity.AcctUser;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * 創立時光:2015-2-6 下晝2:45:14
 * 
 * @author andy
 * @version 2.2
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

 @Autowired
 private SessionFactory sessionFactory;

 private Session getCurrentSession() {
 return this.sessionFactory.getCurrentSession();
 }

 @Override
 public AcctUser load(String id) {
 return (AcctUser) this.getCurrentSession().load(AcctUser.class, id);
 }
 
 @Override
 public AcctUser get(String id) {
 return (AcctUser) this.getCurrentSession().get(AcctUser.class, id);
 }

 @SuppressWarnings("unchecked")
 @Override
 public List<AcctUser> findAll() {
 List<AcctUser> acctUsers = this.getCurrentSession().createQuery("from AcctUser").setCacheable(true).list();
 return acctUsers;
 }

 @Override
 public void persist(AcctUser entity) {
 this.getCurrentSession().persist(entity);

 }

 @Override
 public String save(AcctUser entity) {
 return (String) this.getCurrentSession().save(entity);
 }

 @Override
 public void saveOrUpdate(AcctUser entity) {
 this.getCurrentSession().saveOrUpdate(entity);
 }

 @Override
 public void delete(String id) {
 AcctUser entity = this.load(id);
 this.getCurrentSession().delete(entity);
 }

 @Override
 public void flush() {
 this.getCurrentSession().flush();

 }

}

7、創立Service層

  7.1、Service層接口

package org.andy.work.service;

import java.util.List;

import org.andy.work.entity.AcctUser;

/**
 * 創立時光:2015-2-6 下晝3:18:57
 * 
 * @author andy
 * @version 2.2
 * userService接口
 */

public interface UserService {
 AcctUser load(String id);

 AcctUser get(String id);

 List<AcctUser> findAll();

 void persist(AcctUser entity);

 String save(AcctUser entity);

 void saveOrUpdate(AcctUser entity);

 void delete(String id);

 void flush();
}

  7.2、service層完成類

   UserServiceImpl就須要注入下面界說的Dao層bean。

package org.andy.work.service.impl;

import java.util.List;

import org.andy.work.dao.UserDao;
import org.andy.work.entity.AcctUser;
import org.andy.work.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 創立時光:2015-2-6 下晝3:24:16
 * 
 * @author andy
 * @version 2.2 UserService 的完成
 */
@Service("userService")
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDao userDao;

 @Override
 public AcctUser load(String id) {
 return userDao.load(id);
 }

 @Override
 public AcctUser get(String id) {
 return userDao.get(id);
 }

 @Override
 public List<AcctUser> findAll() {
 return userDao.findAll();
 }

 @Override
 public void persist(AcctUser entity) {
 userDao.persist(entity);
 }

 @Override
 public String save(AcctUser entity) {
 return userDao.save(entity);
 }

 @Override
 public void saveOrUpdate(AcctUser entity) {
 userDao.saveOrUpdate(entity);
 }

 @Override
 public void delete(String id) {
 userDao.delete(id);
 }

 @Override
 public void flush() {
 userDao.flush();
 }

}

8、測試Spring和Hibernate的整合

    我們可以在src/test/java編寫測試類,測試下面的設置裝備擺設,假如測試勝利曾經根本年夜功樂成。

 

package org.andy.work.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.andy.work.entity.AcctUser;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;

/**
 * 創立時光:2015-2-6 下晝3:31:07
 * 
 * @author andy
 * @version 2.2
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
 "classpath:spring-hibernate.xml" })
public class TestUserService {

 private static final Logger LOGGER = Logger
 .getLogger(TestUserService.class);

 @Autowired
 private UserService userService;

 @Test
 public void save() {
 AcctUser acctUser = new AcctUser();
 acctUser.setId(UUID.randomUUID().toString());
 acctUser.setNickName("andy");
 acctUser.setRegisterTime(new Date());
 acctUser.setTelephone("13022221111");
 String id = userService.save(acctUser);
 LOGGER.info(JSON.toJSONString(id));
 }

}

9、引入SpringMVC

     添加spring-mvc.xml文件

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-4.1.xsd 
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

 <!-- 主動掃描@Controller注入為bean -->
 <context:component-scan base-package="org.andy.work.controller" />

 <!-- 以下為SpringMVC設置裝備擺設 -->
 <mvc:annotation-driven>
 <!-- 前往json數據,@response應用 -->
 <mvc:message-converters register-defaults="true">
 <bean
 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
 <property name="supportedMediaTypes">
 <list>
 <value>text/html;charset=UTF-8</value>
 <value>application/json;charset=UTF-8</value>
 </list>
 </property>

 </bean>
 </mvc:message-converters>
 </mvc:annotation-driven>

 <!-- 對模子視圖稱號的解析,即在模子視圖稱號添加前後綴 -->
 <bean
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix" value="/WEB-INF/views" />
 <property name="suffix" value=".jsp" />
 </bean>

</beans>

   下面設置裝備擺設了包掃描Controller,[email protected]��,和視圖層的設置裝備擺設。

10、設置裝備擺設web.xml容器

      web容器是web項目標年夜腦,所以web容器,起首須要引入spring,讓spring治理各個框架,並將其注入為bean。然後設置裝備擺設掌握層的filter信息。而且設置裝備擺設了springmvc攔阻的url為以.hmls開頭的要求。

web.xml文件以下:

 

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 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>springmvc_demo</display-name>

 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
 </context-param>

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

 <!-- openSessionInView設置裝備擺設 感化是延遲session封閉到view層 -->
 <filter>
 <filter-name>openSessionInViewFilter</filter-name>
 <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
 <init-param>
 <param-name>singleSession</param-name>
 <param-value>true</param-value>
 </init-param>
 </filter>

 <!-- 監聽servletContext,啟動contextConfigLocation中的spring設置裝備擺設信息 -->
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- 避免spring內存溢出監聽器 -->
 <listener>
 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 </listener>

 <servlet>
 <description>spring mvc servlet</description>
 <servlet-name>rest</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <!-- 此處設置裝備擺設的是SpringMVC的設置裝備擺設文件 -->
 <param-value>classpath:spring-mvc.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>rest</servlet-name>
 <url-pattern>*.htmls</url-pattern>
 </servlet-mapping>

 <filter-mapping>
 <filter-name>openSessionInViewFilter</filter-name>
 <url-pattern>*.htmls</url-pattern>
 </filter-mapping>

 <!-- 設置裝備擺設session超不時間,單元分鐘 -->
 <session-config>
 <session-timeout>30</session-timeout>
 </session-config>

 <welcome-file-list>
 <welcome-file>/index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

11、創立掌握層Controller

     掌握層UserController

package org.andy.work.controller;

import java.util.List;

import org.andy.work.entity.AcctUser;
import org.andy.work.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/** 
 * 創立時光:2015-2-7 上午11:49:00 
 * @author andy 
 * @version 2.2 
 * 描寫: 用戶Controller
 */
@Controller
@RequestMapping("/user")
public class UserController {

 private static final Logger LOGGER = Logger.getLogger(UserController.class);
 
 @Autowired
 private UserService userService;
 
 @RequestMapping("/showInfo/{userId}")
 public String showUserInfo(ModelMap modelMap, @PathVariable String userId){
 LOGGER.info("查詢用戶:" + userId);
 AcctUser userInfo = userService.load(userId);
 modelMap.addAttribute("userInfo", userInfo);
 return "/user/showInfo";
 }
 
 @RequestMapping("/showInfos")
 public @ResponseBody List<AcctUser> showUserInfos(){
 LOGGER.info("查詢用戶全體用戶");
 List<AcctUser> userInfos = userService.findAll();
 return userInfos;
 }
}

12、創立視圖層

   在src/main/webapp/WEB-INF/views下 創立user/showInfo.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
 + request.getServerName() + ":" + request.getServerPort()
 + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<title>userInfo</title>
</head>
<body>
 用戶信息 昵稱: ${userInfo.nickName} 用戶id:${userInfo.id} 用戶德律風:${userInfo.telephone } 注冊時光:
 <fmt:formatDate value="${userInfo.registerTime }" pattern="yyyy-MM-dd HH:mm:ss" />
 腳色:[
 <c:forEach items="${ userInfo.acctRoles}" var="role">
  ${role.name } 權限[
  <c:forEach items="${ role.acctAuthorities}" var="authority">
  ${authority.name } 
  </c:forEach> ]
  </c:forEach>
 ]

 <br /> ajax顯示全體用戶信息:
 <div id="show_all_user"></div>
</body>
<script type="text/javascript">
 $.ajax({
 type : "get",
 url : "user/showInfos.htmls",
 dataType : "json",
 success : function(data) {
 $(data).each(
 function(i, user) {
 var p = "<p>昵稱:" + user.nickName + " 德律風:"
 + user.telephone + " 注冊時光:"
 + user.registerTime + " id:" + user.id +
 "</p>";
 $("#show_all_user").append(p);
 });
 },
 async : true
 });
</script>
</html>



13、安排辦事器測試

          應用Maven打包安排:clean compile  package

          安排到tomcat,測試
          重要測試下面的  http://localhost:8080/springmvc_hibernate_demo/user/showInfo/6e5afb1d-50e1-45fe-b6fe-b9e399415387.htmls

                                  和http://localhost:8080/springmvc_hibernate_demo/user/showInfos.htmls  (json數據前往)
          下面視圖層就包括了這兩條url要求的測試:

     ok,到此Spring+SpringMVC+Hibernate搭建終了。

博客起源:http://blog.csdn.net/fengshizty?viewmode=list

項目源碼:http://download.csdn.net/detail/fengshizty/8432647

願望能贊助有須要的同伙,後續持續彌補相干材料,感謝年夜家對本站的支撐!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved