国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

SSH框架整合——基于XML配置文件

2019-11-11 02:38:49
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

SSH框架整合——基于xml配置文件

@(SPRing)[spring, struts2, hibernate, 框架整合, ssh, Spring]

SSH框架整合基于XML配置文件SSH框架整合SSH框架整合的基本環(huán)境準(zhǔn)備第一步創(chuàng)建web項(xiàng)目引入jar包第二步引入框架的配置文件第三步創(chuàng)建包結(jié)構(gòu)和類(lèi)第四步將Service和DAO交給Spring管理第五步引入頁(yè)面SSH整合Struts2和Spring的整合第六步修改頁(yè)面鏈接為Struts2所能匹配的格式第七步編寫(xiě)Action中的listCustomer方法第八步Struts2和Spring整合方式一Action由Struts2自身創(chuàng)建第八步Struts2和Spring整合方式二Action交給Spring管理推薦第九步在客戶(hù)Service中使用客戶(hù)DaoSSH整合Hibernate和Spring的整合第十步Hibernate和Spring整合方式一帶hibernate的配置文件第十步Hibernate和Spring整合方式二不帶hibernate的配置文件推薦第十一步添加事務(wù)管理Hibernate的模板的API使用Hibernate的模板完成CRUD的操作完成增刪改的操作完成查詢(xún)的操作配置opensessionInView過(guò)濾器解決Hibernate懶加載問(wèn)題配置全站編碼過(guò)濾器

SSH框架整合

該SSH整合是基于Spring4、Struts2、Hibernate5的。

SSH框架整合的基本環(huán)境準(zhǔn)備

第一步:創(chuàng)建web項(xiàng)目,引入jar包

標(biāo)紅為整合必須引入的

Struts2

struts-2.3.24/apps/struts2-blank/WEB-INF/lib*.jar —Struts2基本開(kāi)發(fā)包 這里寫(xiě)圖片描述struts2-convention-plugin-2.3.24.jar —Struts2的注解開(kāi)發(fā)包struts2-spring-plugin-2.3.24.jar —Struts2整合Spring的開(kāi)發(fā)包struts2-json-plugin-2.3.24.jar —Struts2整合Ajax的開(kāi)發(fā)包javax.servlet.jsp.jstl-1.2.1.jar — java標(biāo)準(zhǔn)標(biāo)簽庫(kù)

Hibernate

MySQL-connector-java-5.1.7-bin.jar —數(shù)據(jù)庫(kù)驅(qū)動(dòng)hibernate-release-5.0.7.Final/lib/required*.jar —Hibernate必須包 這里寫(xiě)圖片描述日志記錄 這里寫(xiě)圖片描述c3p0連接池 這里寫(xiě)圖片描述

注意:在struts2基礎(chǔ)包和Hibernate5基礎(chǔ)包中javassist-x.jar這個(gè)包會(huì)有沖突,搭環(huán)境時(shí)請(qǐng)使用Hibernate中的高版本javassist的包

Spring Spring的基本開(kāi)發(fā)包 這里寫(xiě)圖片描述Spring的AOP的開(kāi)發(fā)包 這里寫(xiě)圖片描述Spring整合web項(xiàng)目包:spring-web-4.2.4.RELEASE.jarSpring整合Junit項(xiàng)目包 spring-test-4.2.4.RELEASE.jarjunit-4.9.jarSpring的JDBC模板包:spring-jdbc-4.2.4.RELEASE.jarSpring事務(wù)管理包:spring-tx-4.2.4.RELEASE.jarSpring整合Hibernate:spring-orm-4.2.4.RELEASE.jar整合c3p0連接池:com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar,需要使用c3p0連接池,可以導(dǎo)入。

如果使用有hibernate配置文件的ssh整合,使用c3p0連接池,需要使用hibernate中c3p0可選包中的三個(gè)jar包; 如果使用沒(méi)有hibernate配置文件的ssh整合,使用c3p0連接池,需要使用spring整合c3p0連接池中的jar包。 兩者不可同用,否則會(huì)有沖突。

第二步:引入框架的配置文件

Struts2 web.xml<!-- Struts核心過(guò)濾器 --><filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern></filter-mapping>struts.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts></struts>Hibernate hibernate.cfg.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> </session-factory></hibernate-configuration>映射文件<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package=""></hibernate-mapping>Spring web.xml<!-- 配置Spring上下文環(huán)境 --><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>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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"></beans>log4j.properties### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=c/:mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.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=info, stdout

第三步:創(chuàng)建包結(jié)構(gòu)和類(lèi)

package com.pc.crm.domain;import java.io.Serializable;/** * 客戶(hù)實(shí)體類(lèi) * @author Switch */public class Customer implements Serializable { private static final long serialVersionUID = 8501538130746309236L;}package com.pc.crm.web.action;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;import com.pc.crm.domain.Customer;/** * 客戶(hù)Action * @author Switch */public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { private static final long serialVersionUID = 7878143682430064108L; Customer customer = new Customer(); @Override public Customer getModel() { return this.customer; }}package com.pc.crm.service;/** * 客戶(hù)服務(wù)接口 * @author Switch */public interface CustomerService {}package com.pc.crm.service.impl;import com.pc.crm.service.CustomerService;/** * 客戶(hù)服務(wù)實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerServiceImpl implements CustomerService {}package com.pc.crm.dao;/** * 客戶(hù)持久層接口 * @author Switch */public interface CustomerDao {}package com.pc.crm.dao.impl;import com.pc.crm.dao.CustomerDao;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl implements CustomerDao {}

第四步:將Service和DAO交給Spring管理

<!-- 配置客戶(hù)服務(wù)bean --><bean id="customerService" class="com.pc.crm.service.impl.CustomerServiceImpl"></bean><!-- 配置客戶(hù)持久層bean --><bean id="customerDao" class="com.pc.crm.dao.impl.CustomerDaoImpl"></bean>

第五步:引入頁(yè)面

這里只給出一個(gè)訪問(wèn)鏈接,基于JSP的。

<a href="${pageContext.request.contextPath}/customer/listCustomer">客戶(hù)列表</a>

SSH整合:Struts2和Spring的整合

第六步:修改頁(yè)面鏈接為Struts2所能匹配的格式

<a href="${pageContext.request.contextPath}/customer/list_Customer.action">客戶(hù)列表</a>

第七步:編寫(xiě)Action中的listCustomer方法

package com.pc.crm.web.action;import java.util.List;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;import com.pc.crm.domain.Customer;import com.pc.crm.service.CustomerService;/** * 客戶(hù)Action * @author Switch */public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { private static final long serialVersionUID = 7878143682430064108L; // 客戶(hù)服務(wù)類(lèi) CustomerService customerService; // 用于使用值棧特性,在頁(yè)面中使用 List<Customer> customers = null; public List<Customer> getCustomers() { return customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } // 模型驅(qū)動(dòng) Customer customer = new Customer(); @Override public Customer getModel() { return this.customer; } /** * 顯示客戶(hù)列表 * @return */ public String listCustomer() { // 從數(shù)據(jù)庫(kù)中獲客戶(hù)列表 customers = customerService.findAllCustomer(); // 轉(zhuǎn)發(fā)到客戶(hù)列表視圖 return "list"; }}

第八步:Struts2和Spring整合方式一:Action由Struts2自身創(chuàng)建

引入Struts2和Spring整合的插件包 struts2-spring-plugin-2.3.24.jar

該jar包下有一個(gè)struts-plugin.xml的文件,在該文件中開(kāi)啟了Spring工廠對(duì)Action中的屬性按照名稱(chēng)自動(dòng)裝配等功能。

<!-- Make the Spring object factory the automatic default --><constant name="struts.objectFactory" value="spring" />

該常量在struts2核心包的default.properties文件中,有如下配置

### if specified, the default object factory can be overridden here### Note: short-hand notation is supported in some cases, such as "spring"### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here# struts.objectFactory = spring### specifies the autoWiring logic when using the SpringObjectFactory.### valid values are: name, type, auto, and constructor (name is the default)struts.objectFactory.spring.autoWire = name### indicates to the struts-spring integration if Class instances should be cached### this should, until a future Spring release makes it possible, be left as true### unless you know exactly what you are doing!### valid values are: true, false (true is the default)struts.objectFactory.spring.useClassCache = true### ensures the autowire strategy is always respected.### valid values are: true, false (false is the default)struts.objectFactory.spring.autoWire.alwaysRespect = false### By default SpringObjectFactory doesn't support AOP### This flag was added just temporally to check if nothing is broken### See https://issues.apache.org/jira/browse/WW-4110struts.objectFactory.spring.enableAopSupport = false

當(dāng)struts.objectFactory常量啟用時(shí),開(kāi)啟對(duì)Spring的一系列支持。比如說(shuō)按名自動(dòng)裝配。

在Action中不需要使用原來(lái)的工廠獲取,提供set方法即可。// 注入客戶(hù)服務(wù)類(lèi)CustomerService customerService;public void setCustomerService(CustomerService customerService) { this.customerService = customerService;}/** * customerService未優(yōu)化 *//* public CustomerAction() { ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()); customerService = context.getBean("customerService", CustomerService.class);}*/配置Action:Action是Struts2自身創(chuàng)建<package name="customer" extends="struts-default" namespace="/customer"> <!-- 形如list_Customer --> <action name="*_*" class="com.pc.crm.web.action.CustomerAction" method="{1}{2}"> <!-- 轉(zhuǎn)發(fā)到客戶(hù)列表視圖 --> <result name="list" type="dispatcher">/jsp/customer/list.jsp</result> </action></package>

第八步:Struts2和Spring整合方式二:Action交給Spring管理(推薦)

引入Struts2和Spring整合的插件包

struts2-spring-plugin-2.3.24.jar

將Action交給Spring創(chuàng)建

<!-- 配置Action,Action注入屬性,必須手工注入,且必須聲明為多例 --><!-- 客戶(hù)Action --><bean id="customerAction" class="com.pc.crm.web.action.CustomerAction" scope="prototype"> <property name="customerService" ref="customerService" /></bean>

注意的事項(xiàng)

一定要將Action配置為多例的屬性的注入必須手動(dòng)完成

struts.xml文件中對(duì)應(yīng)actionclass屬性為beanid屬性

<package name="customer" extends="struts-default" namespace="/customer"> <!-- 形如list_Customer --> <action name="*_*" class="customerAction" method="{1}{2}"> <!-- 轉(zhuǎn)發(fā)到客戶(hù)列表視圖 --> <result name="list" type="dispatcher">/jsp/customer/list.jsp</result> </action></package>

第九步:在客戶(hù)Service中使用客戶(hù)Dao

package com.pc.crm.service.impl;import java.util.List;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;import com.pc.crm.service.CustomerService;/** * 客戶(hù)服務(wù)實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerServiceImpl implements CustomerService { // 注入客戶(hù)Dao private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } @Override public List<Customer> findAllCustomer() { // 查找客戶(hù)列表 return customerDao.findAllCustomer(); }}<!-- 配置客戶(hù)服務(wù)bean --><bean id="customerService" class="com.pc.crm.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"/></bean>

SSH整合:Hibernate和Spring的整合

第十步:Hibernate和Spring整合方式一:帶hibernate的配置文件

創(chuàng)建實(shí)體類(lèi)和映射文件Customer.hbm.xmlpackage com.pc.crm.domain;import java.io.Serializable;/** * 客戶(hù)實(shí)體類(lèi) * @author Switch */public class Customer implements Serializable { private static final long serialVersionUID = 8501538130746309236L; private Long custId; private String custName; private String custSource; private String custIndustry; private String custLevel; private String custAddress; private String custPhone; ......}<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.pc.crm.domain"> <class name="Customer" table="cst_customer" lazy="true" batch-size="3"> <id name="custId" column="cust_id" type="java.lang.Long"> <generator class="native"/> </id> <property name="custName" column="cust_name" type="java.lang.String" length="32"/> <property name="custSource" column="cust_source" type="java.lang.String" length="32"/> <property name="custIndustry" column="cust_industry" type="java.lang.String" length="32"/> <property name="custLevel" column="cust_level" type="java.lang.String" length="32"/> <property name="custAddress" column="cust_address" type="java.lang.String" length="128"/> <property name="custPhone" column="cust_phone" type="java.lang.String" length="64"/> </class></hibernate-mapping>配置hibernate.cfg.xml配置文件<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- 1、連接數(shù)據(jù)庫(kù)的基本信息 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mycrm</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.passWord">123456</property> <!-- 數(shù)據(jù)庫(kù)的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 2、hibernate的基本配置 --> <!-- 是否顯示SQL語(yǔ)句 --> <property name="hibernate.show_sql">true</property> <!-- 是否格式化顯示SQL語(yǔ)句 --> <property name="hibernate.format_sql">true</property> <!-- 采用何種策略來(lái)創(chuàng)建表結(jié)構(gòu): --> <!-- update:檢查表結(jié)構(gòu)和實(shí)體類(lèi)映射文件的變化,如果發(fā)現(xiàn)映射文件和表結(jié)構(gòu)不一致,更新表結(jié)構(gòu)。 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置hibernate使用連接池:告知Hibernate使用連接池的廠商 --> <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!-- 3、映射文件的位置 --> <mapping resource="com/pc/crm/domain/Customer.hbm.xml" /> <mapping resource="com/pc/crm/domain/LinkMan.hbm.xml" /> </session-factory></hibernate-configuration>在Spring中引入Hibernate的配置文件<!-- 配置Hibernate的SessionFactory,有hibernate配置文件 --><bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"/></bean>Spring為了簡(jiǎn)化Hibernate的開(kāi)發(fā),提供了Hibernate的模板package com.pc.crm.dao.impl;import java.util.List;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public List<Customer> findAllCustomer() { }}<!-- 配置客戶(hù)持久層bean --><bean id="customerDao" class="com.pc.crm.dao.impl.CustomerDaoImpl"> <!-- 該bean繼承了HibernateDaoSupport,則可以直接注入sessionFactory --> <property name="sessionFactory" ref="sessionFactory"/></bean>在客戶(hù)Dao中使用Hibernate的模板package com.pc.crm.dao.impl;import java.util.List;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public List<Customer> findAllCustomer() { return (List<Customer>) this.getHibernateTemplate().find("from Customer"); }}

第十步:Hibernate和Spring整合方式二:不帶hibernate的配置文件(推薦)

創(chuàng)建實(shí)體類(lèi)和映射文件Customer.hbm.xmlpackage com.pc.crm.domain;import java.io.Serializable;/** * 客戶(hù)實(shí)體類(lèi) * @author Switch */public class Customer implements Serializable { private static final long serialVersionUID = 8501538130746309236L; private Long custId; private String custName; private String custSource; private String custIndustry; private String custLevel; private String custAddress; private String custPhone; ......}<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.pc.crm.domain"> <class name="Customer" table="cst_customer" lazy="true" batch-size="3"> <id name="custId" column="cust_id" type="java.lang.Long"> <generator class="native"/> </id> <property name="custName" column="cust_name" type="java.lang.String" length="32"/> <property name="custSource" column="cust_source" type="java.lang.String" length="32"/> <property name="custIndustry" column="cust_industry" type="java.lang.String" length="32"/> <property name="custLevel" column="cust_level" type="java.lang.String" length="32"/> <property name="custAddress" column="cust_address" type="java.lang.String" length="128"/> <property name="custPhone" column="cust_phone" type="java.lang.String" length="64"/> </class></hibernate-mapping>替換hibernate.cfg.xml中的相關(guān)內(nèi)容,將其配置在spring中 提供數(shù)據(jù)庫(kù)屬性文件db.propertiesjdbc.driverClass=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mycrmjdbc.user=rootjdbc.password=123456配置屬性持有對(duì)象<!-- 配置屬性持有對(duì)象 --><context:property-placeholder location="classpath:db.properties"/>配置數(shù)據(jù)源<!-- 配置數(shù)據(jù)源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/></bean>替換hibernate配置信息<!-- 配置Hibernate的SessionFactory,無(wú)hibernate配置文件 --><bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 配置數(shù)據(jù)源 --> <property name="dataSource" ref="dataSource"/> <!-- 配置hibernate屬性--> <property name="hibernateProperties"> <props> <!-- 數(shù)據(jù)庫(kù)的方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- 是否顯示SQL語(yǔ)句 --> <prop key="hibernate.show_sql">true</prop> <!-- 是否格式化顯示SQL語(yǔ)句 --> <prop key="hibernate.format_sql">true</prop> <!-- 采用何種策略來(lái)創(chuàng)建表結(jié)構(gòu): --> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 配置映射文件 --> <property name="mappingLocations" value="classpath:com/pc/crm/domain/*.hbm.xml"/></bean>Spring為了簡(jiǎn)化Hibernate的開(kāi)發(fā),提供了Hibernate的模板package com.pc.crm.dao.impl;import java.util.List;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public List<Customer> findAllCustomer() { }}<!-- 配置客戶(hù)持久層bean --><bean id="customerDao" class="com.pc.crm.dao.impl.CustomerDaoImpl"> <!-- 該bean繼承了HibernateDaoSupport,則可以直接注入sessionFactory --> <property name="sessionFactory" ref="sessionFactory"/></bean>在客戶(hù)Dao中使用Hibernate的模板package com.pc.crm.dao.impl;import java.util.List;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public List<Customer> findAllCustomer() { return (List<Customer>) this.getHibernateTemplate().find("from Customer"); }}

第十一步:添加事務(wù)管理

配置事務(wù)管理器<!-- 配置事務(wù)管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/></bean>配置事務(wù)通知<!-- 配置事務(wù)通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 事務(wù)管理策略,查為只讀 --> <!-- 事務(wù)隔離級(jí)別:mysql為可重復(fù)讀,事務(wù)傳播行為:默認(rèn)值required --> <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/> <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/> <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/> <tx:method name="*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/> </tx:attributes></tx:advice>配置事務(wù)AOP<!-- 配置事務(wù)AOP --><aop:config> <aop:pointcut expression="execution(* com.pc.crm.service.impl.*.*(..))" id="pointcut1"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/></aop:config>

PS:如果需要配置基于注解的事務(wù),請(qǐng)參考之前的博文《Spring事務(wù)管理》。

Hibernate的模板的API

使用Hibernate的模板完成CRUD的操作

完成增刪改的操作

Serializable save(Object obj);void update(Object obj);void delete(Object obj);package com.pc.crm.dao.impl;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public void save(Customer customer) { this.getHibernateTemplate().save(customer); } @Override public void update(Customer customer) { this.getHibernateTemplate().update(customer); } @Override public void delete(Customer customer) { this.getHibernateTemplate().delete(customer); }}

完成查詢(xún)的操作

T get(Class c,Serializable id); / T load(Class c,Serializable id);Listpackage com.pc.crm.dao.impl;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.pc.crm.dao.CustomerDao;import com.pc.crm.domain.Customer;/** * 客戶(hù)持久層接口實(shí)現(xiàn)類(lèi) * @author Switch */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public Customer findById(Long id) { return this.getHibernateTemplate().load(Customer.class, id); } @Override public List<Customer> findAll() { // 使用HQL查詢(xún): // List<Customer> list = (List<Customer>) this.getHibernateTemplate().find("from Customer "); // 使用QBC查詢(xún):使用DetchedCriteria // DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class); // List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(detachedCriteria); // 命名查詢(xún): List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByNamedQuery("queryAll"); return list; } @Override public List<Customer> findByPage() { DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class); List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(detachedCriteria, 0, 3); return list; }}

配置openSessionInView過(guò)濾器,解決Hibernate懶加載問(wèn)題

<!-- 配置openSessionInView,解決Hibernate懶加載問(wèn)題 --><filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern></filter-mapping>

PS:將該過(guò)濾器放在Struts2核心過(guò)濾器上面。

配置全站編碼過(guò)濾器

<!-- 配置全站編碼過(guò)濾器 --><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> <!-- 是否強(qiáng)制使用該編碼 --> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param></filter><filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

PS:將該過(guò)濾器放在Struts2核心過(guò)濾器上面。


發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 西乌珠穆沁旗| 长汀县| 黑龙江省| 承德市| 达州市| 河西区| 永川市| 清流县| 乌拉特前旗| 中山市| 长治县| 堆龙德庆县| 大港区| 哈尔滨市| 会东县| 房产| 汉阴县| 凤冈县| 上饶县| 通榆县| 高台县| 莎车县| 阳新县| 右玉县| 贡觉县| 新河县| 安阳市| 镇坪县| 镇原县| 乃东县| 玉屏| 顺义区| 泾阳县| 临洮县| 衡东县| 响水县| 浪卡子县| 大姚县| 莆田市| 和平区| 柘荣县|