前段时间,刚做了自己第一个使用这三个框架的简单的系统,现在有点时间,来整理一下,希望对其他朋友有帮助,不废话了……
说明下我使用的版本:
hibernate 4.1.1.Final
spring 3.1.1.RELEASE
struts 2.2.3
使用mysql数据库(当然其他的数据库也差不多)
1.我这里首先配置hibernate,一般应用lib\required下面的包应该够用了,把它们放到web工程的web-inf/lib下面,因为使用到spring管理hibernate,所以这里就不用hibernate.hbm.xml了
2.配置spring
选取dist文件夹下面包
org.springframework.asm-3.1.1.RELEASE.jar -----asm 程序
org.springframework.beans-3.1.1.RELEASE.jar----spring管理benas,实现依赖注入
org.springframework.context-3.1.1.RELEASE.jar------spring-context 的扩展支持
org.springframework.core-3.1.1.RELEASE.jar-------核心包
org.springframework.expression-3.1.1.RELEASE.jar -----spring表达式语言
org.springframework.orm-3.1.1.RELEASE.jar------spring 整合第三方的 ORM 映射支持,如 Hibernate 、Ibatis、Jdo 以及spring的JPA的支持。
org.springframework.transaction-3.1.1.RELEASE.jar-----spring事务管理
org.springframework.web-3.1.1.RELEASE.jar------springWeb 下的工具包
--------------------------下面是数据源需要的包,我这里使用c3p0数据源,当然你可以选择apache的dbcp 等等------------------------------------
c3p0-0.9.1.2.jar
mysql-connector-java-5.0.8-bin.jar --- 数据库驱动包
当然根据你的需要导入其他包,放到web-inf/lib下面,下面开始配置spring的xml:applicationContext.xml(这个文件放在src下面)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 注解支持 -->
<context:annotation-config />
<!--C3P0 数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- 指定连接数据库的驱动 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<!-- 指定连接数据库的URL -->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8"/>
<!-- 指定连接数据库的用户名 -->
<property name="user" value="root"/>
<!-- 指定连接数据库的密码 -->
<property name="password" value=""/>
<!-- 指定连接数据库连接池的最大连接数 -->
<property name="maxPoolSize" value="500"/>
<!-- 指定连接数据库连接池的最小连接数 -->
<property name="minPoolSize" value="10"/>
<!-- 指定连接数据库连接池的初始化连接数 -->
<property name="initialPoolSize" value="5"/>
<!-- 指定连接数据库连接池的连接的最大空闲时间 -->
<property name="maxIdleTime" value="60"/>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="0"/>
<!-- 在当前连接数耗尽的时候,一次获取的新的连接数 -->
<property name="acquireIncrement" value="3"/>
</bean>
<!--hibernate sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<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">false</prop>
</props>
</property>
<!-- mapping 文件列表 -->
<property name="mappingResources">
<list>
<value>cn/mike/domain/test.hbm.xml</value>
</list>
</property>
</bean>
<!-- 测试配置 -->
<bean id="testService" class="cn.mike.service.impl.TestServiceImpl"></bean>
<bean id="test" class="cn.mike.domain.Test">
<property name="id" value="2" />
<property name="name" value="mike" />
</bean>
<bean id="testAction" class="cn.mike.web.action.TestAction"></bean>
</beans>
我在test数据库下面创建test数据表,就2个字段:id,name 上面的配置中test.hbm.xml(我放在cn.mike.domain下面,你可以根据你的需要更改)就是这个数据表的映射,内容如下
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.mike.domain">
<class name="Test" table="test">
<id name="id">
<generator class="native" />
</id>
<property name="name" type="string">
<column name="name" length="32"/>
</property>
</class>
</hibernate-mapping>
Test这个类就是一个简单的bean,如下
package cn.mike.domain;
public class Test {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
以上就是一些spring和hibernate的基本配置,外加一个测试类Test而已,下面把bean交给spring容器管理,我这里写了一个hibernate工具类,让很多基本操作交给它
public final class HibernateUtil {
/*
* hibernate 工具类
* 集成操作:1.保存,2.更新,3.删除,4.按页获取数据,5.按ID获取数据,6.获取总记录数,7.获取总页数
*/
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public Session getSession(){
return sessionFactory.openSession();
}
/*
* 公用操作
*/
//保存
public void save(Object obj){
Session session = null;
Transaction trans = null;
try{
session = this.getSession();
trans = session.beginTransaction();
session.save(obj);
trans.commit();
}catch(HibernateException e){
if(null != trans)
trans.rollback();
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
}
//删除
public void delete(Object obj){
Session session = null;
Transaction trans = null;
try{
session = this.getSession();
trans = session.beginTransaction();
session.delete(obj);
trans.commit();
}catch(HibernateException e){
if(null != trans)
trans.rollback();
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
}
//更新
public void update(Object obj){
Session session = null;
Transaction trans = null;
try{
session = this.getSession();
trans = session.beginTransaction();
session.update(obj);
trans.commit();
}catch(HibernateException e){
if(null != trans)
trans.rollback();
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
}
//根据ID获取数据
@SuppressWarnings("rawtypes")
public Object get(Class clazz,Serializable id){
Session session = null;
Object obj = null;
try{
session = this.getSession();
obj = session.get(clazz,id);
}catch(HibernateException e){
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
return obj;
}
//按页获取数据
@SuppressWarnings("unchecked")
public List<Object> getDataByPage(int currPage,int perPageRecord,String table){
Session session = null;
List<Object> list = null;
String hql = "from "+table;
try{
session = this.getSession();
Query query = session.createQuery(hql);
query.setFirstResult((currPage-1)*perPageRecord);
query.setMaxResults(perPageRecord);
list = query.list();
}catch(HibernateException e){
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
return list;
}
//获取全部数据
@SuppressWarnings("unchecked")
public List<Object> getData(String table){
Session session = null;
List<Object> list = null;
String hql = "from "+table;
try{
session = this.getSession();
Query query = session.createQuery(hql);
list = query.list();
}catch(HibernateException e){
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
return list;
}
//获取总记录数:传入(表对应的类名)
public int getTotalCount(String table){
Session session = null;
String hql = "select count(*) from "+table;
int totalCount = 0;
try{
session = this.getSession();
Query query = session.createQuery(hql);
totalCount = ((Number)query.uniqueResult()).intValue();
}catch(HibernateException e){
e.printStackTrace();
throw e;
}finally{
if(null != session)
session.close();
}
return totalCount;
}
//获取总页数:传入(表对应的类名,每页总记录数)
public int getTotalPage(String table,int pageSize) {
return ((this.getTotalCount(table)+pageSize)-1)/pageSize;
}
}
在applicationContext.xml里面配置这个工具类
<bean id="hibernateUtil" class="cn.mike.dao.HibernateUtil">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
接下来我们测试下这两个框架的整合情况,当然很多朋友会遇到各种各样的错误,我还是希望大家自己去解决,那样对你的帮助很大,当然也存在我写的东西不是很明确。
public class TestServiceImpl {
@Resource private HibernateUtil hibernateUtil;
public void save(Test test) {
}
public void update(Test test) {
}
public void delete(Test test) {
}
public List<Test> getData() {
List list = hibernateUtil.getDataByPage(1, 10, "Test");
return list;
}
}
大家建立一个测试单元junit来测试,我这里建立的如下(当然大家需要导入junit包)
public class TestSpring {
/*
* spring框架测试类
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void test() {
List<cn.mike.domain.Test> list = null;
try {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
TestService testService = (TestService)ctx.getBean("testService");
list = testService.getData();
} catch (BeansException e) {
e.printStackTrace();
}
Iterator<cn.mike.domain.Test> it = list.iterator();
cn.mike.domain.Test test;
while(it.hasNext()){
test = it.next();
System.out.println(test.getId()+","+test.getName());
}
}
}
上面就是spring和hibernate的了,遇到错误的朋友留言或者BAIDU GOOGLE吧,不过还是希望你们自己能解决
2.下面合成struts2
web.xml这样写
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>shop</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts -->
<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.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
其他的我想对struts2熟悉的朋友struts.XML很容易配置,先写到这里了,如果对struts2不熟悉,建议先单个框架学习,再集合