Struts2.3+Hibernate4.3+Spring4.0整合

Struts2.3+Hibernate4.3+Spring4.0整合

整个工程的结构如下


1. 导入需要的jar包



2.web.xml 和 struts.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Struts Blank</display-name>

	<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>/*.action</url-pattern>
	</filter-mapping>
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:Application-*.xml</param-value>
	</context-param>
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

struts.xml(这里我添加了一个自己的ResgisterAction.java)

<?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>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true" />

	<package name="zjh" namespace="/" extends="struts-default">	

		<global-results>
			<result name="error">/error.jsp</result>
		</global-results>

		<global-exception-mappings>
			<exception-mapping exception="java.lang.Exception"
				result="error" />
		</global-exception-mappings>
		
		<!--这里放置自己的action  -->
		<action name="RegisterAction" class="com.zjh.action.RegisterAction">
			<result name="success">/index.jsp</result>
		</action>
	</package>
</struts>

3. Application-Commom.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:jdbc="http://www.springframework.org/schema/cache" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/jdbc/spring-cache.xsd">

	<!-- 扫描指定包 -->
	<context:component-scan base-package="com.*" />
	<context:annotation-config />

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${jdbc.driverClass}" />
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
		<property name="user" value="root" />
		<property name="password" value="root" />
		<property name="minPoolSize" value="5" />
		<property name="maxPoolSize" value="50" />
		<property name="maxIdleTime" value="1800" />
		<property name="acquireIncrement" value="2" />
		<property name="maxStatements" value="0" />
		<property name="initialPoolSize" value="10" />
		<property name="idleConnectionTestPeriod" value="30" />
		<property name="acquireRetryAttempts" value="30" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>com/zjh/model/UserInfo.hbm.xml</value>
			</list>
		</property>

		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${jdbc.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.use_sql_comments">true</prop>
				<prop key="hibernate.hbm2ddl.auto">create</prop>
			</props>
		</property>
	</bean>

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 配置事务管理器 -->
	<!--//对hibernate4进行实物的管理 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory">
		</property>
	</bean>

	<!-- 配置事务的传播特性 -->
	<!-- 配置事务的属性 对应的方法等等 AOP通知,事务的边界告诉方法,不是完整的事务切面。 -->

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>

			<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="remove*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="update*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="modify*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="submit*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="insert*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="save*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="Update*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="Insert*" propagation="REQUIRED"
				rollback-for="Exception" />
		</tx:attributes>
	</tx:advice>

	<!-- 配置哪些类哪些方法使用事务 proxy-target-class="true" spring的声明式事务(最常用) -->
	<aop:config>
		<aop:pointcut id="allManagerMethod"
			expression="execution(* com.common.dao.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" />
	</aop:config>
</beans>

4. jdbc.peoperties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.jdbcUrl=jdbc\:mysql\://localhost\:3306/chat
jdbc.username=name
jdbc.password=passwd

5. 可以在SessionFactory中看到,有一个UserInfo.hbm.xml,这是自定义的hibernate映射文件。

UserInfo.java

package com.zjh.model;

public class UserInfo {
	private int id;
	private String name;
	private String nick_name;
	private String baiDuYun_Id;
	private String tag;

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

	public String getNick_name() {
		return nick_name;
	}

	public void setNick_name(String nick_name) {
		this.nick_name = nick_name;
	}

	public String getBaiDuYun_Id() {
		return baiDuYun_Id;
	}

	public void setBaiDuYun_Id(String baiDuYun_Id) {
		this.baiDuYun_Id = baiDuYun_Id;
	}

	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}
}

UserInfo.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.zjh.model">
	<class name="UserInfo" table="user_info">
		<id name="id" column="id" type="int">
			<generator class="native" />
		</id>
		<property name="name" />
		<property name="nick_name" />
		<property name="baiDuYun_Id" />
		<property name="tag" />
	</class>
</hibernate-mapping>


6.当然,有了UserInfo ,怎么能少了Dao呢?

 1)BaseDao

package com.common.dao;

import java.util.List;

import org.junit.Test;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

public interface BaseDAO<T>{
 public void add(T t);

 public void update(T t);

 public void delete(T t);

 public List findByProperty(String className, String property, Object value);
}


它的实现

package com.common.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.common.dao.BaseDAO;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDAO<T> {
	
	public void add(T t) {
		this.getHibernateTemplate().save(t);
	}

	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}

	public void delete(T t) {
		this.getHibernateTemplate().delete(t);
	}

	public List findByProperty(String className, String property, Object value) {
		String queryString = "select " + property + " from " + className
				+ " as model where model." + property + " = ?";
		System.out.println(queryString);
		List list = this.getSessionFactory().openSession()
				.createQuery(queryString).setParameter(0, value).list();
		return list;
	}
}


2)UserInfoDao

package com.zjh.dao;

import java.util.List;

import com.common.dao.BaseDAO;
import com.zjh.model.UserInfo;

public interface UserInfoDao extends BaseDAO<UserInfo> {
	public List<String> findByUserName(String value);

	public List<String> findByUserNickName(String value);

	public List<String> findByUserBaiDuYunId(String value);

	public List<String> findByUserTag(String value);
}


它的实现类

package com.zjh.dao.impl;

import java.util.List;

import com.common.dao.impl.BaseDaoImpl;
import com.zjh.dao.UserInfoDao;
import com.zjh.model.UserInfo;

public class UserInfoDaoImpl extends BaseDaoImpl<UserInfo> implements
		UserInfoDao {
	private static final String USER_INFO_NAME = "name";
	private static final String USER_INFO_NICK_NAME = "nick_name";
	private static final String USER_INFO_BAIDUYUNID = "baiDuYun_Id";
	private static final String USER_INFO_TAG = "tag";
	private static final String USER_INFO_CLASS = UserInfo.class.getName();

	public List<String> findByUserName(String value) {
		return this.findByProperty(USER_INFO_CLASS, USER_INFO_NAME, value);
	}

	public List<String> findByUserNickName(String value) {
		return this.findByProperty(USER_INFO_CLASS, USER_INFO_NICK_NAME, value);
	}

	public List<String> findByUserBaiDuYunId(String value) {
		return this
				.findByProperty(USER_INFO_CLASS, USER_INFO_BAIDUYUNID, value);
	}

	public List<String> findByUserTag(String value) {
		return this.findByProperty(USER_INFO_CLASS, USER_INFO_TAG, value);
	}
}


7.有了model,有了dao,那么还得有配置文件

Application-Dao.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:jdbc="http://www.springframework.org/schema/cache" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/jdbc/spring-cache.xsd">

	<bean name="baseDao" class="com.common.dao.impl.BaseDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<bean name="userInfoDao" class="com.zjh.dao.impl.UserInfoDaoImpl" parent="baseDao">
	</bean>
</beans>


Application-Model.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:jdbc="http://www.springframework.org/schema/cache" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/jdbc/spring-cache.xsd">

	<!-- <bean id="person" class="com.common.model.Person"></bean> -->
	
	<bean id="userInfo" class="com.zjh.model.UserInfo"></bean>
</beans>


8.测试一下

package com.zjh.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.common.dao.BaseDAO;
import com.zjh.dao.UserInfoDao;
import com.zjh.model.UserInfo;

public class Test {
	String application[] = { "Application-Common.xml", "Application-Dao.xml","Application-Model.xml" };

	@org.junit.Test
	public void testBaseDao() {
		ApplicationContext ac = new ClassPathXmlApplicationContext(application);
		UserInfoDao dao = (UserInfoDao)ac.getBean("userInfoDao");
		UserInfo user = new UserInfo();
		user.setBaiDuYun_Id("123");
		user.setName("zjh");
		user.setNick_name("zjh");
		user.setTag("test");
		dao.add(user);

		List list = dao.findByUserName("zjh");
		for (Object u : list) {
			System.out.println(u);
		}
	}
}


至此,完成了所需的全部工作。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值