天天看點

SpringMVC+Hibernate架構整合

Eclipse-建立一個Dynamic Web Project,目錄結構如下:

SpringMVC+Hibernate架構整合

包結構功能說明:

(1)entity包:放置項目中的實體類(一個表一個類)

(2)util工具包:各種工具類(StringHelper類)

----------M層-----------

(3)dao接口包:各種操作接口類(ICRM_UserDao)

(4)dao.impl 實作接口包:各種實作操作接口的實作類(CRM_UserDaoImpl)

(5)service接口包:業務實作的接口(ICRM_UserService)

(6)service.impl實作業務接口的實作類(CRM_UserServiceImpl)

(7)controller包:控制器實作類(CRM_UserController)(C層)

架構項目包之間的引用關系:

使用者請求-->controller-->service包-->dao包-->db

搭建ssh架構

1.下載下傳SpringMVC和Hibernate架構:Spring架構和SpringMVC架構,他們是天然內建。

springmvc官網http://projects.spring.io/spring-framework/改版後不可以直接下載下傳,可利用maven下載下傳,或者去csdn或github上下載下傳

hibernate下載下傳位址:http://hibernate.org/orm/downloads/

SpringMVC+Hibernate架構整合

     線上安裝SpringMVC插件

     http://dist.springsource.com/release/TOOLS/update/e4.4/

     線上安裝Hibernate Tools插件

     http://download.jboss.org/jbosstools/neon/stable/updates/

2.導入SSH架構整合的jar包(在WebContent\WEB-INF\lib目錄下)

    2.1導入SpringMVC的jar包;

    2.2導入Hibernate的jar包

    2.3導入三方依賴的jar包    commons-logging-1.2.jar

    2.4導入mysql驅動包   mysql-connector-java-6.0.5.jar

3.配置web.xml(在WebContent\WEB-INF\web.xml目錄下)

    3.1配置Spring IOC容器

    <!-- 配置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>

同時在項目根目錄右擊建立Spring Bean Configuration File檔案名為config,新增applicationContext.xml檔案

SpringMVC+Hibernate架構整合

     3.2配置Springmvc的控制器DispatcherServlet

      <!-- 配置Springmvc的DispatcherServlet -->

<servlet>

<servlet-name>dispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<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>*.action</url-pattern>

</servlet-mapping>

同時在config目錄下建立springmvc.xml

   3.3配置編碼方式 過濾器 

    <!-- 配置編碼方式 過濾器 ,注意要配置所有的過濾器,最前面 -->

<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>*.action</url-pattern>

</filter-mapping>

    3.4配置HiddenHttpMethodFilter(為了實作REST full)

    <!-- 為了使用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>*.action</url-pattern>

</filter-mapping>

4.配置SpringMVC配置(config\springmvc.xml)

       4.1導入命名空間

SpringMVC+Hibernate架構整合

4.2配置掃描的包(config\springmvc.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:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd

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.3.xsd">

<!-- 配置自動掃描的包 -->

<context:component-scan base-package="com.myFlows"

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>

</beans>

4.3配置視圖解析器

<!-- 配置視圖解析器 -->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/"></property>

<property name="suffix" value=".jsp"></property>

</bean>

4.4配置靜态資源

<!-- 配置靜态資源 -->

<mvc:default-servlet-handler/>

4.5 注釋

<!-- 注釋 -->

<mvc:annotation-driven />

5.配置Spring(config\applicationContext.xml)

5.1導入命名空間

SpringMVC+Hibernate架構整合

5.2配置自動掃描包

<!-- 配置自動掃描的包 -->

<context:component-scan base-package="com.myFlows" 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>

5.3配置資料源

<!-- 配置資料源 -->

<context:property-placeholder location="classpath:db.properties"/>

config目錄下建立檔案db.properties 添加如下内容:

jdbc.user=root

jdbc.password=root

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/myflow

5.4配置datasource

在WEB-INF\lib下導入C3p0的jar包(hibernate-release-5.2.9.Final\hibernate-release-5.2.9.Final\lib\optional\c3p0)

<!-- 配置datasource -->

<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">

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

5.5整合Hibernate

    5.5.1配置SessionFactory

    <!-- 配置 SessionFactory -->

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

id="sessionFactory">

<!-- 配置資料源 -->

<property name="dataSource" ref="dataSource"></property>

<!-- 掃描的實體包(pojo) -->

<property name="namingStrategy">

<bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>

</property>

<property name="packagesToScan" value="com.myFlows.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>

       5.5.2配置Hibernate的事務管理器 

      <!-- 配置Hibernate的事務管理器 -->

<bean id="transactionManager"

class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

6.SSH整合測試    

6.1建立test測試包

SpringMVC+Hibernate架構整合

     6.2建立一個Junit測試類

(test包右擊-new -other-JUnit-JUnit Test Case-TestSSH)

package com.myFlows.test;

import static org.junit.Assert.*;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSSH {

@Test

public void test() {

fail("Not yet implemented");

}

private ApplicationContext ctx = null;

@Test

public void testDataSource() {

ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

System.out.println(ctx);

}

}

運作測試一下:

備注1:報錯Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception i...

經檢查是配置檔案applicationContext.xml檔案的hibernate 的版本不對,去網上下載下傳了hibernate-release-4.3.11.Final.zip這個版本,把以前5版本的jar包替換成4版本的,解決問題。

備注2:報錯java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

解決方法:db.properties檔案中jdbc.jdbcUrl=jdbc:mysql://localhost:3306/myflow改為jdbc.jdbcUrl=jdbc:mysql://localhost:3306/myflow?serverTimezone=UTC ,解決問題

最終正确運作:

SpringMVC+Hibernate架構整合

6.3測試資料源

@Test

public void testDataSource() {

ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

System.out.println(ctx);

DataSource datasource=ctx.getBean(DataSource.class);

System.out.println(datasource);

try {

System.out.println(datasource.getConnection().toString());

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

運作結果:

SpringMVC+Hibernate架構整合

6.4測試SessionFactory

SessionFactory sessionFactory= ctx.getBean(SessionFactory.class);

System.out.println(sessionFactory);

 運作結果:

[email protected]

6.5測試操作資料庫表(session)

SpringMVC+Hibernate架構整合

根據資料庫表寫實體類:(User.java為例)

注:表中屬性id為自動生成的,故設定alter table `user` change `id` `id` int auto_increment

其中構造函數可以用點選Source->Generate Constructor using Fields....自動生成

get函數和set函數可以用點選Source->Generate Getters and Setters.....自動生成

package com.myFlows.entity;

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

//注解實體類,資料庫表名為user

@Entity

@Table(name="user")

public class User implements Serializable{

//注解id表示自動生成的

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

private int id;

private String user_id;

private String user_pass;

private String user_name;

private String user_email;

private String user_phone;

private int  created_time;

public User() {

}

public User(String user_id, String user_pass, String user_name, String user_email, String user_phone,

int created_time) {

super();

this.user_id = user_id;

this.user_pass = user_pass;

this.user_name = user_name;

this.user_email = user_email;

this.user_phone = user_phone;

this.created_time = created_time;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getUser_id() {

return user_id;

}

public void setUser_id(String user_id) {

this.user_id = user_id;

}

public String getUser_pass() {

return user_pass;

}

public void setUser_pass(String user_pass) {

this.user_pass = user_pass;

}

public String getUser_name() {

return user_name;

}

public void setUser_name(String user_name) {

this.user_name = user_name;

}

public String getUser_email() {

return user_email;

}

public void setUser_email(String user_email) {

this.user_email = user_email;

}

public String getUser_phone() {

return user_phone;

}

public void setUser_phone(String user_phone) {

this.user_phone = user_phone;

}

public long getCreated_time() {

return created_time;

}

public void setCreated_time(int created_time) {

this.created_time = created_time;

}

}

TestSSH.java中添加資料庫測試

Session session= sessionFactory.openSession();

Transaction tx=session.beginTransaction();

//資料庫的操作

User user=new User("bbb","123456","zhouge","[email protected]","12344444",121);

session.save(user);

tx.commit();

session.close();

運作結果:

SpringMVC+Hibernate架構整合

同時檢視資料庫表:(我多運作了幾次)

SpringMVC+Hibernate架構整合

此時測試操作資料庫表成功!!!

附1:TestSSH.java代碼:

package com.myFlows.test;

import static org.junit.Assert.fail;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.myFlows.entity.User;

public class TestSSH {

// @Test

// public void test() {

// fail("Not yet implemented");

// }

private ApplicationContext ctx = null;

@Test

public void testDataSource() {

ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

//System.out.println(ctx);

DataSource datasource=ctx.getBean(DataSource.class);

System.out.println(datasource);

try {

System.out.println(datasource.getConnection().toString());

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

SessionFactory sessionFactory= ctx.getBean(SessionFactory.class);

System.out.println(sessionFactory);

Session session= sessionFactory.openSession();

Transaction tx=session.beginTransaction();

//資料庫的操作

User user=new User("bbb","123456","zhouge","[email protected]","12344444",121);

session.save(user);

tx.commit();

session.close();

}

}

附2:web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

id="WebApp_ID" version="3.1">

<display-name>myFlows</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>

<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>*.action</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>*.action</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>*.action</url-pattern>

</filter-mapping>

</web-app>

附3:

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: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.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<!-- 配置自動掃描的包 -->

<context:component-scan base-package="com.myFlows"

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 class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">

<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 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

id="sessionFactory">

<!-- 配置資料源 -->

<property name="dataSource" ref="dataSource"></property>

<!-- 掃描的實體包(pojo) -->

<property name="namingStrategy">

<bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>

</property>

<property name="packagesToScan" value="com.myFlows.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>

附4;springmvc.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:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd

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.3.xsd">

<!-- 配置自動掃描的包 -->

<context:component-scan base-package="com.myFlows"

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>

<!-- 配置視圖解析器 -->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/"></property>

<property name="suffix" value=".jsp"></property>

</bean>

<!-- 配置靜态資源 -->

<mvc:default-servlet-handler/>

<!-- 注釋 -->

<mvc:annotation-driven />

</beans>

繼續閱讀