Struts2+Spring3+Hibernate3导包
Struts2导包与配置
Struts2/apps/struts2-blank.war/WEB-INF/lib/*.jar 如下图所示: 导入与Spring整合的jar包- struts2-spring-plugin-2.3.15.1.jar 用于Struts2整合Spring
- struts2-json-plugin-2.3.15.1.jar 用于Struts2整合AJAX
- struts2-convention-plugin-2.3.15.1.jar 用于Struts使用注解
<filter>在src下新建struts.xml(也可以从Struts2/apps/struts2-blank.war/WEB-INF/classes下拷贝)
<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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
</package>
Spring导包与配置
Spring3.2开发最基本的jar包- spring-beans-3.2.0.RELEASE.jar
- spring-context-3.2.0.RELEASE.jar
- spring-core-3.2.0.RELEASE.jar
- spring-expression-3.2.0.RELEASE.jar
- com.springsource.org.apache.commons.logging-1.1.1.jar
- com.springsource.org.apache.log4j-1.2.15.jar
- spring-aop-3.2.0.RELEASE.jar
- spring-aspects-3.2.0.RELEASE.jar
- com.springsource.org.aopalliance-1.0.0.jar
- com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
- spring-jdbc-3.2.0.RELEASE.jar
- spring-tx-3.2.0.RELEASE.jar
- spring-tx-3.2.0.RELEASE.jar
- spring-orm-3.2.0.RELEASE.jar
- spring-web-3.2.0.RELEASE.jar
- spring-test-3.2.0.RELEASE.jar
<!-- 配置Spring的监听器 -->在applicationContext.xml中引入aop、tx、context约束(具体可以从dist包中的xsd-config.html中进行拷贝)
<listener>
<!-- 监听器默认加载的是WEB-INF/applicationContext.xml -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring框架的配置文件所在的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<?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">
</beans>
log4j.properties
### direct log messages to stdout ###在Servlet/Filter中获得Spring上下文对象
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 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' ###
log4j.rootLogger=off, stdout
WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(servletContext);
Hibernate的导包与配置
需要导入的jar包如下 解压根目录/hibernate3.jar 解压根目录/lib/required/*.jar 如下图所示解压根目录/lib/jpa/hibernate-jpa-2.0-api-1.0.1.Final.jar 数据库连接池c3p0—解压根目录/lib/optional/c3p0/c3p0-0.9.1.jar 整合log4j: slf4j-log4j12-1.7.2.jar(需单独下载) 、log4j-1.2.16.jar(在Spring导包时已经导入) 使用二级缓存Ehcache(需单独下载,解压后):
- commons-logging.jar(在Spring导包时已导入)
- backport-util-concurrent.jar
- ehcache-1.5.0.jar
- mysql-connector-java-5.0.8-bin.jar
Configurationconfiguration = new Configuration().configure();hibernate.cfg.xml的约束可以在hibernate3.jar/org.hibernate/hibernate-configuration-3.0.dtd中找到复制拷贝即可
SessionFactorysessionFactory= configuration.buildSessionFactory();
Sessionsession = sessionFactory.openSession()/ getCurrentSession();
Transactiontransaction = session.beginTransaction();
数据库操作
transaction.commit();
<!DOCTYPE hibernate-configuration PUBLIC至于持久类映射文件的约束可以在 hibernate3.jar/org.hibernate/hibernate-mapping-3.0.dtd中找到复制到 *.hbm.xml中即可。
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
创建包结构
- ssh1.test.action
- ssh1.test.dao
- ssh1.test.service
- ssh1.test.vo
<s:form action="book_add" namespace="/" method="post" theme="simple">创建BookService、BookDao、BookAction 配置struts.xml
图书名称:<s:textfield name="name"/><br/>
图书价格:<s:textfield name="price"/><br/>
<s:submit value="添加图书"/>
</s:form>
Struts2和Spring整合的两种方式
方式一: 由Struts2自己管理Action
导入struts2-spring-plugin-x.x.x.jar Action对象的创建由Struts2自己管理 在struts.xml中配置Action<package name="default" namespace="/" extends="struts-default">这种方式在Action中获取Service时只需要在Action中声明一Service变量 然后再提供一个Setter方法 并在applicationContext.xml中注册一下Service即可。然后由Struts2自己创建Action后就会自动按照名称为Action注入Service 如下所示在applicationContext.xml中需如下进行配置:
<action name="book_*" class="ssh1.test.action.BookAction"
method="{1}"></action>
</package>
<bean id="bookService" class="ssh1.test.service.BookService">之所以Struts2会自动按照名称为Action注入名称对应的Service 是因为在struts2-spring-plugin-x.x.x.jar下有一配置文件: struts-plugin.xml 在此文件中开启了如下常量
<property name="bookDao" ref="bookDao" />
</bean>
<bean id="bookDao" class="ssh1.test.dao.BookDao" />
<constant name="struts.objectFactory" value="spring" />引发了另一个常量的执行:(Spring的工厂类按照名称自动注入)
struts.objectFactory.spring.autoWire = name
方式二: Action的创建交由Spring进行管理
也需要导入struts2-spring-plugin-x.x.x.jar 可以在struts.xml中的对应的<action>标签上通过一个伪类名方式进行配置<package name="default" namespace="/" extends="struts-default">在applicationContext.xml中配置和伪类名相同的Bean
<action name="book_*" class="bookAction" method="{1}"></action>
</package>
<!-- 配置Action -->
<bean id="bookAction" class="ssh1.test.action.BookAction" scope="prototype">
<property name="bookService" ref="bookService" />
</bean>
<!-- Service的配置 -->
<bean id="bookService" class="ssh1.test.service.BookService">
<property name="bookDao" ref="bookDao" />
</bean>
<!-- DAO的配置 -->
<bean id="bookDao" class="ssh1.test.dao.BookDao" />
推荐使用第二种方式,在Spring中管理的类,可以对其进行AOP开发,统一的管理
注意:由Sping统一管理创建Action时 一定要声明为scope="prototype" 否则会有线程安全问题
Spring整合Hibernate
整合方式一:零障碍整合(含有hibernate.cfg.xml)
具体源代码可以上我的GitHub上下载 https://github.com/LX1993728/ssh1 可以在Spring中引入Hibernate的配置文件 1. 通过LocalSessionFactoryBean在spring中直接引用Hibernate的配置文件<!-- 零障碍整合 在Spring配置文件中引入Hibernate的配置文件 -->2. Spring提供了Hibernate的模板,只需要将HibernateTemplate模板注入给DAO(前提是DAO继承自HibernateDaoSupport),注意:注入sessionFactory便可自动设置Hibernate模板
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<!-- DAO的配置 -->改写DAO,继承自HibernateDaoSupport
<bean id="bookDao" class="ssh1.test.dao.BookDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
public class BookDao extends HibernateDaoSupport {3.创建一个持久化类的映射文件(Book.hbm.xml)
public void save(Book book) {
System.out.println("DAO层保存图书");
this.getHibernateTemplate().save(book);
}
}
<hibernate-mapping>4.使用HibernateTransactionManager管理Spring事务
<class name="ssh1.test.vo.Book" table="book">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" />
<property name="price" />
</class>
</hibernate-mapping>
<!-- 管理事务 -->5.使用<tx:annotation-driven>开启注解事务
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 注解开启事务 -->项目名myspring_ssh1 具体代码如下:
<tx:annotation-driven transaction-manager="transactionManager" />
代码如下: Book
package ssh1.test.vo;Book.hbm.xml
public class Book {
private Integer id;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
<?xml version="1.0" encoding="UTF-8"?>BookDao
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ssh1.test.vo.Book" table="book">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" />
<property name="price" />
</class>
</hibernate-mapping>
package ssh1.test.dao;BookService
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import ssh1.test.vo.Book;
public class BookDao extends HibernateDaoSupport {
public void save(Book book) {
System.out.println("DAO层保存图书");
this.getHibernateTemplate().save(book);
}
}
package ssh1.test.service;BookAction
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ssh1.test.dao.BookDao;
import ssh1.test.vo.Book;
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
public class BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void add(Book book) {
System.out.println("Service层保存图书......");
bookDao.save(book);
}
}
package ssh1.test.action;struts.xml
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ssh1.test.service.BookService;
import ssh1.test.vo.Book;
public class BookAction extends ActionSupport implements ModelDriven<Book> {
private BookService bookService;
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
// 模型驱动类
private Book book=new Book();
public Book getModel() {
return book;
}
// 请求处理的方法
public String add() {
System.out.println("web层的方法添加执行了......");
bookService.add(book);
return NONE;
}
}
<?xml version="1.0" encoding="UTF-8" ?>hibernate.cfg.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="book_*" class="bookAction" method="{1}"></action>
</package>
</struts>
<?xml version="1.0" encoding="UTF-8"?>applicationContext.xml
<!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>
<!-- 必须配置的属性 -->
<!-- 配置数据库连接池的基本信息 -->
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql:///ssh1
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- Hibernate的方言 -->
<!-- 不同的数据库,生成的底层的SQL语句是不同的 -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- 可选的属性 -->
<!-- 显示SQL -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化SQL -->
<property name="hibernate.format_sql">true</property>
<property name="hibernate.connection.autocommit">false</property>
<!-- hbm: 映射 to DDL: create drop alter -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- C3P0连接池设定 -->
<!-- 使用c3po连接池 配置连接池提供的供应商 -->
<property name="connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!--在连接池中可用的数据库连接的最少数目 -->
<property name="c3p0.min_size">5</property>
<!--在连接池中所有数据库连接的最大数目 -->
<property name="c3p0.max_size">20</property>
<!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位 -->
<property name="c3p0.idle_test_period">3000</property>
<!-- 通知Hibernate加载那些映射文件 -->
<mapping resource="ssh1/test/vo/Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>log4j.properties
<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">
<!-- 零障碍整合 在Spring配置文件中引入Hibernate的配置文件 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<!-- 配置Action -->
<bean id="bookAction" class="ssh1.test.action.BookAction" scope="prototype">
<property name="bookService" ref="bookService" />
</bean>
<!-- Service的配置 -->
<bean id="bookService" class="ssh1.test.service.BookService">
<property name="bookDao" ref="bookDao" />
</bean>
<!-- DAO的配置 -->
<bean id="bookDao" class="ssh1.test.dao.BookDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 管理事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 注解开启事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
### direct log messages to stdout ###addBook.jsp
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 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' ###
log4j.rootLogger=info, stdout
<%@ page language="java" contentType="text/html; charset=UTF-8"web.xml
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>添加图书</h1>
<s:form action="book_add" namespace="/" method="post" theme="simple" >
图书名称:<s:textfield name="name" /><br>
图书价格:<s:textfield name="price"/>
<s:submit value="添加图书"/>
</s:form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>运行结果如下
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置Spring的监听器 -->
<listener>
<!-- 监听器默认加载的是WEB-INF/applicationContext.xml -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring框架的配置文件所在的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
方式二: 没有Hibernate配置文件的形式
不再需要Hibernate配置文件的形式,将Hibernate配置文件的信息直接配置到Spring中。 Hibernate配置文件的信息包括: 连接数据库基本参数、Hibernate常用属性、连接池和映射 将Hibernate配置文件相关的信息整合到Spring中 1.连接池<!-- 引入外部属性文件 -->2.配置Hibernate常用属性以及持久化类映射文件
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"HibernateTemplate的API
class="org.springframework.orm.hibernate3.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>
<prop key="hibernate.autocommit">false</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
<!-- 加载映射 -->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:ssh2/test/vo</value>
</list>
</property>
</bean>
- Serializable save(Object entity):保存数据
- void update(Object entity) :修改数据
- void delete(Object entity) :删除数据
- <T> T get(Class<T> entityClass, Serializable id):根据ID进行检索.立即检索
- <T> T load(Class<T> entityClass, Serializable id) :根据ID进行检索.延迟检索.
- List find(String queryString, Object... values) :支持HQL查询.直接返回List集合.
- List findByCriteria(DetachedCriteria criteria) :离线条件查询.
- List findByNamedQuery(String queryName, Object... values):命名查询的方式.
<filter>新建项目myspring3_ssh2 项目结构如下:
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
具体实现代码如下:有兴趣的可以上我GitHub上下载https://github.com/LX1993728/ssh2 Book
package ssh2.test.vo;Book.hbm.xml
public class Book {
private Integer id;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>BookDao
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ssh2.test.vo.Book" table="book">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" />
<property name="price" />
</class>
<query name="findByName">
from Book where name = ?
</query>
</hibernate-mapping>
package ssh2.test.dao;BookService
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import ssh2.test.vo.Book;
public class BookDao extends HibernateDaoSupport {
public void save(Book book) {
System.out.println("DAO层保存图书");
this.getHibernateTemplate().save(book);
}
public void update(Book book) {
this.getHibernateTemplate().update(book);
}
public void delete(Book book) {
this.getHibernateTemplate().delete(book);
}
public Book findById(Integer id) {
return this.getHibernateTemplate().get(Book.class, id);
}
public List<Book> findAll() {
return this.getHibernateTemplate().find("from Book");
}
public List<Book> findByCriteria(DetachedCriteria criteria) {
return this.getHibernateTemplate().findByCriteria(criteria);
}
public List<Book> findByName(String name) {
return this.getHibernateTemplate().findByNamedQuery("findByName", name);
}
public Book findByIdLazy(Integer id) {
return this.getHibernateTemplate().load(Book.class, id);
}
}
package ssh2.test.service;BookAction
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ssh2.test.dao.BookDao;
import ssh2.test.vo.Book;
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
public class BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void add(Book book) {
System.out.println("Service层保存图书......");
bookDao.save(book);
}
public void update(Book book) {
bookDao.update(book);
}
public void delete(Book book) {
bookDao.delete(book);
}
public Book findById(Integer id) {
return bookDao.findById(id);
}
public List<Book> findAll() {
return bookDao.findAll();
}
public List<Book> findByCriteria(DetachedCriteria criteria) {
return bookDao.findByCriteria(criteria);
}
public List<Book> findByName(String name) {
return bookDao.findByName(name);
}
public Book findByIdLazy(Integer id) {
return bookDao.findByIdLazy(id);
}
}
package ssh2.test.action;SSHTest
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ssh2.test.service.BookService;
import ssh2.test.vo.Book;
public class BookAction extends ActionSupport implements ModelDriven<Book> {
private BookService bookService;
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
// 模型驱动类
private Book book=new Book();
public Book getModel() {
return book;
}
// 请求处理的方法
public String add() {
System.out.println("web层的方法添加执行了......");
bookService.add(book);
return NONE;
}
}
package ssh2.test.junitDemo;struts.xml
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import ssh2.test.service.BookService;
import ssh2.test.vo.Book;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SSHTest {
@Autowired
@Qualifier("bookService")
private BookService bookService;
@Test
public void demo1() {
Book book = new Book();
book.setId(1);
book.setName("Java从入门到精通");
book.setPrice(98d);
bookService.update(book);
}
@Test
public void demo2() {
Book book = new Book();
book.setId(1);
bookService.delete(book);
}
@Test
public void demo3() {
Book book = bookService.findById(2);
System.out.println(book);
}
@Test
public void demo4() {
List<Book> books = bookService.findAll();
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void demo5() {
DetachedCriteria criteria = DetachedCriteria.forClass(Book.class);
criteria.add(Restrictions.eq("name", "Struts2开发入门"));
List<Book> books = bookService.findByCriteria(criteria);
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void demo6() {
List<Book> books = bookService.findByName("SSH整合2");
for (Book book : books) {
System.out.println(book);
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>log4j.properties
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="book_*" class="bookAction" method="{1}"></action>
</package>
</struts>
### direct log messages to stdout ###jdbc.proeprties
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 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' ###
log4j.rootLogger=info, stdout
jdbc.driver=com.mysql.jdbc.DriverapplicationContext.xml
jdbc.url=jdbc:mysql:///ssh2
jdbc.user=root
jdbc.password=root
<?xml version="1.0" encoding="UTF-8"?>web.xml
<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">
<!-- 没有引入Hibernate配置文件 -->
<!-- 连接池信息 -->
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 无Hibernate配置文件整合 在Spring配置文件中引入Hibernate应该配置的信息 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.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>
<prop key="hibernate.autocommit">false</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
<!-- 加载映射 -->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:ssh2/test/vo</value>
</list>
</property>
</bean>
<!-- 配置Action -->
<bean id="bookAction" class="ssh2.test.action.BookAction" scope="prototype">
<property name="bookService" ref="bookService" />
</bean>
<!-- Service的配置 -->
<bean id="bookService" class="ssh2.test.service.BookService">
<property name="bookDao" ref="bookDao" />
</bean>
<!-- DAO的配置 -->
<bean id="bookDao" class="ssh2.test.dao.BookDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 管理事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 注解开启事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
<?xml version="1.0" encoding="UTF-8"?>addBook.jsp
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Spring的监听器 -->
<listener>
<!-- 监听器默认加载的是WEB-INF/applicationContext.xml -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring框架的配置文件所在的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"部署项目后访问如下
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>添加图书</h1>
<s:form action="book_add" namespace="/" method="post" theme="simple">
图书名称:<s:textfield name="name"/><br/>
图书价格:<s:textfield name="price"/><br/>
<s:submit value="添加图书"/>
</s:form>
</body>
</html>
为了方便测试 多添加了几条数据 如下:
依次测试demo1~demo6
方式三:纯注解实现三大框架整合
导入以上项目的全部jar包,还需要Struts2-convention-plugin.x.x.x.jar(用于Struts2的注解开发) 配置web.xml(配置spring的监听器以及配置文件所在的位置、配置Struts2的核心控制过滤器) 使用@Action、@Controller以及@Scope标注Action类,使用@Action以及@Result标注处理请求的方法。并在Action类中使用@Autowired和@Qualifier注入Service类。 使用@Service和@Transactional标注Service类,并使用@Autowired和@Qualifier注入Dao类。 使用@Repository标注DAO类,还需要声明注入HibernateTemplate模板。 使用@Entity和@Table标注持久化类,使用@Id和@GeneratedValue标注主键属性,使用@Column标注普通属性(注意注解要使用javax.persistence.*包下的注解类) 去除struts.xml和hibernate.cfg.xml 保留applicationContext.xml,添加jdbc.properties和log4j.properties. 配置applicationContext.xml 1.配置扫描指定包下的注解<!-- 扫描添加注解的类 -->2.配置连接池
<context:component-scan
base-package="ssh3.test.action,ssh3.test.dao,ssh3.test.service" />
<!-- 连接池信息 -->3.使用AnnotationSessionFactoryBean配置Hibernate属性与映射扫描
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 无Hibernate配置文件整合 在Spring配置文件中引入Hibernate应该配置的信息 -->4.最后配置Hibernate模板与事务管理
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- 管理连接池 -->
<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>
<prop key="hibernate.autocommit">false</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
<!-- 映射扫描 -->
<property name="packagesToScan">
<list>
<value>ssh3.test.vo</value>
</list>
</property>
</bean>
<!-- 配置Hibernate模板 -->新建项目myspring3_ssh3 下载地址:https://github.com/LX1993728/ssh3 具体代码如下所示:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 管理事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 注解开启事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
Book
package ssh3.test.vo;BookDao
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name")
private String name;
// 注意: 实体类中的属性即使不使用注解,默认也会自动生成和属性名相同的字段
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
package ssh3.test.dao;BookService
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import ssh3.test.vo.Book;
@Repository("bookDao")
public class BookDao {
@Autowired
@Qualifier("hibernateTemplate")
HibernateTemplate hibernateTemplate;
public void save(Book book) {
System.out.println("DAO层保存图书");
hibernateTemplate.save(book);
}
}
package ssh3.test.service;BookAction
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ssh3.test.dao.BookDao;
import ssh3.test.vo.Book;
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
@Service("bookService")
public class BookService {
@Autowired
@Qualifier("bookDao")
private BookDao bookDao;
public void add(Book book) {
System.out.println("Service层保存图书......");
bookDao.save(book);
}
}
package ssh3.test.action;jdbc.properties
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ssh3.test.service.BookService;
import ssh3.test.vo.Book;
//<package namespace="/" extends="strtus-default">
@Namespace("/")
@ParentPackage("struts-default")
@Controller("bookAction")
@Scope("prototype")
public class BookAction extends ActionSupport implements ModelDriven<Book> {
// 模型驱动类
private Book book = new Book();
public Book getModel() {
return book;
}
// 在Action中注入Service
@Autowired
@Qualifier("bookService")
private BookService bookService;
// 请求处理的方法
@Action(value = "book_add")
public String add() {
System.out.println("web层的方法添加执行了......");
bookService.add(book);
return NONE;
}
}
jdbc.driver=com.mysql.jdbc.Driverlog4j.properties
jdbc.url=jdbc:mysql:///ssh3
jdbc.user=root
jdbc.password=root
### direct log messages to stdout ###applicationContext.xml
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 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' ###
log4j.rootLogger=info, stdout
<?xml version="1.0" encoding="UTF-8"?>web.xml
<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:component-scan
base-package="ssh3.test.action,ssh3.test.dao,ssh3.test.service" />
<!-- 连接池信息 -->
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 无Hibernate配置文件整合 在Spring配置文件中引入Hibernate应该配置的信息 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- 管理连接池 -->
<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>
<prop key="hibernate.autocommit">false</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
<!-- 映射扫描 -->
<property name="packagesToScan">
<list>
<value>ssh3.test.vo</value>
</list>
</property>
</bean>
<!-- 配置Hibernate模板 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 管理事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 注解开启事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
<?xml version="1.0" encoding="UTF-8"?>addBook.jsp
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Spring的监听器 -->
<listener>
<!-- 监听器默认加载的是WEB-INF/applicationContext.xml -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring框架的配置文件所在的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"运行测试 成功 需要注意的是:使用注解的话 Spring的版本要在4.0以上 否则启动时就会有异常
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>添加图书</h1>
<s:form action="book_add" namespace="/" method="post" theme="simple">
图书名称:<s:textfield name="name"/><br/>
图书价格:<s:textfield name="price"/><br/>
<s:submit value="添加图书"/>
</s:form>
</body>
</html>