文章目录
Spring4_Day04
SSH整合方式一:无障碍整合
1. 引入jar包
2. 引入配置文件
- hibernate.efg.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">
- 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">
- 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
- log4g.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
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 mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.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' ###
# error warn info debug trace
log4j.rootLogger= info, stdout
3. 创建包结构
4. 创建相关类
5. 引入相关页面
6. Spring整合Struts方式一
- 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="customerService" class="com.lld.ssh.service.impl.CustomerServiceImpl">
</bean>
</beans>
- 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>
<package name="ssh1" extends="struts-default" namespace="/">
<action name="customer_*" class="com.lld.ssh.web.action.CustomerAction" method="{1}"></action>
</package>
</struts>
6. Spring整合Struts方式二
- 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 将service交给Spring管理 -->
<bean id="customerService" class="com.lld.ssh.service.impl.CustomerServiceImpl">
</bean>
<!-- 将Action交给Spring管理 开启多例scope="prototype" -->
<bean id="CustomerAction" class="com.lld.ssh.web.action.CustomerAction" scope="prototype">
<!-- 需要在这里将属性注入 -->
<property name="customerService" ref="customerService"></property>
</bean>
</beans>
- 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>
<!-- <package name="ssh1" extends="struts-default" namespace="/">
<action name="customer_*" class="com.lld.ssh.web.action.CustomerAction" method="{1}"></action>
</package> -->
<package name="ssh1" extends="struts-default" namespace="/">
<!-- 将Action交给Spring管理后,需要将class里面的值改成Spring配置Action的id -->
<action name="customer_*" class="CustomerAction" method="{1}"></action>
</package>
</struts>
7. 将Dao交给Spring进行管理
<!-- 将Dao交给Spring进行管理 -->
<bean id="customerdao" class="com.lld.ssh.dao.impl.CustomerDaoImpl">
</bean>
8. Spring整合Hibernate框架
- 创建数据库和表
Create database ssh1;
Use ssh1;
CREATE TABLE `cst_customer` (
`cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
`cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
`cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
`cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
`cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
`cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话',
`cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话',
PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
- 编写实体和映射
<?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>
<!-- 建立类与表的映射 -->
<class table="cst_customer" name="com.lld.ssh.domain.Customer">
<!-- 主键属性对应 -->
<id name="cust_id" column="cust_id">
<!-- 主键生成策略 -->
<generator class="native"></generator>
</id>
<!-- 其余键属性对应 -->
<property name="cust_name" column="cust_name" length="32" />
<property name="cust_source" column="cust_source" length="32"/>
<property name="cust_industry" column="cust_industry"/>
<property name="cust_level" column="cust_level"/>
<property name="cust_phone" column="cust_phone"/>
<property name="cust_mobile" column="cust_mobile"/>
</class>
</hibernate-mapping>
-
Spring和Hibernate整合
- Dao继承HibernateDaoSupport
package com.lld.ssh.dao.impl;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.lld.ssh.dao.CustomerDao;
import com.lld.ssh.domain.Customer;
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
@Override
public void save(Customer customer) {
System.out.println("customerDao的save方法执行了.....");
this.getHibernateTemplate().save(customer);
}
}
* 将Hibernate配置文件引入Spring配置文件
<!-- 引入Hibernate的配置的信息=============== -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 引入hibernate的配置文件 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
* 在配置Dao的时候直接注入sessionFactory
<!-- 将Dao交给Spring进行管理 -->
<bean id="customerdao" class="com.lld.ssh.dao.impl.CustomerDaoImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
* 在Dao中直接使用
public void save(Customer customer) {
System.out.println("customerDao的save方法执行了.....");
this.getHibernateTemplate().save(customer);
}
9. 配置Spring的事务管理
- 配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
- 开启注解事务
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
- 在业务层使用注解:在service层的类上添加@Transactional
package com.lld.ssh.service.impl;
import org.springframework.transaction.annotation.Transactional;
import com.lld.ssh.dao.CustomerDao;
import com.lld.ssh.domain.Customer;
import com.lld.ssh.service.CustomerService;
@Transactional
public class CustomerServiceImpl implements CustomerService {
private CustomerDao customerdao;
public void setCustomerdao(CustomerDao customerdao) {
this.customerdao = customerdao;
}
@Override
public void save(Customer customer) {
System.out.println("CustomerService的save方法执行了");
customerdao.save(customer);
}
}
SSH整合方式二:将Hibernate交给Spring管理(没有Hibernate配置文件)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入外部属性文件=============================== -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置C3P0连接池=============================== -->
<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.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Spring整合Hibernate -->
<!-- 引入Hibernate的配置的信息=============== -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 注入连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的相关属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 设置映射文件 -->
<property name="mappingResources">
<list>
<value>com/itheima/ssh/domain/Customer.hbm.xml</value>
</list>
</property>
</bean>
<!-- 配置Action=================== -->
<bean id="customerAction" class="com.itheima.ssh.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"/>
</bean>
<!-- 配置Service================== -->
<bean id="customerService" class="com.itheima.ssh.service.impl.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
<!-- 配置DAO====================== -->
<bean id="customerDao" class="com.itheima.ssh.dao.impl.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssh1
jdbc.username=root
jdbc.password=abc
Hibernate模板使用
package com.lld.ssh.dao.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.lld.ssh.dao.CustomerDao;
import com.lld.ssh.domain.Customer;
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);
}
@Override
public Customer get(Long cus_id) {
return this.getHibernateTemplate().get(Customer.class, cus_id);
}
@Override
public Customer load(Long cus_id) {
// TODO Auto-generated method stub
return this.getHibernateTemplate().load(Customer.class, cus_id);
}
@Override
public List<Customer> findAllByHQL() {
return (List<Customer>) this.getHibernateTemplate().find("from Customer");
}
@Override
public List<Customer> findByQBC() {
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
return (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);
}
@Override
public List<Customer> findByNameQuery() {
return (List<Customer>) this.getHibernateTemplate().findByNamedQuery("findByNamedQuery");
}
}
package com.lld.ssh.test;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lld.ssh.dao.CustomerDao;
import com.lld.ssh.domain.Customer;
import com.lld.ssh.service.CustomerService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class demo1 {
@Resource(name="customerService")
private CustomerService customerService;
@Test
/**
* 删除用户
*/
public void demo01(){
Customer customer = customerService.get(1l);
customerService.delete(customer);
}
@Test
/**
* 更新用户
*/
public void demo02(){
Customer customer = customerService.get(1l);
customer.setCust_name("张渣");
customerService.update(customer);
}
@Test
/**
* 查找用户
*/
public void demo03(){
List<Customer> findByQBC = customerService.findByQBC();
for (Customer customer : findByQBC) {
System.out.println(customer);
}
}
@Test
/**
* 查找用户
*/
public void demo04(){
List<Customer> findByHQL = customerService.findAllByHQL();
for (Customer customer : findByHQL) {
System.out.println(customer);
}
}
@Test
/**
* 查找用户
*/
public void demo05(){
List<Customer> findByNameQuery = customerService.findByNameQuery();
for (Customer customer : findByNameQuery) {
System.out.println(customer);
}
}
}
延迟加载解决方案
解决方案
- 配置一个过滤器,在struts过滤器前面配置
<?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>ssh1</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的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载Spring的配置文件的路径的,默认加载的/WEB-INF/applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 解决延迟加载问题的过滤器 -->
<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>
<!-- Struts2的核心过滤器 -->
<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>
</web-app>