`
Reverie夜
  • 浏览: 20408 次
  • 性别: Icon_minigender_1
  • 来自: 惠州
社区版块
存档分类
最新评论

SSH案例

    博客分类:
  • JAVA
阅读更多

~Spring+Strtus2+Hibernate的整合案例~

项目结构:ლ(╹◡╹ლ)请无视过滤器、监听器以及CKEdtior等……


 

 配置文件都在WEI-INF下,web.xml和applicationContext.xml主要配置↓↓↓↓↓↓↓↓↓↓↓↓↓↓

web.xml:

 

<!-- 启动服务器时,实例化Spring容器 -->
	<context-param>
	    <param-name>contextConfigLocation</param-name>
		<!-- 指定Listener要加载的Spring配置文件 -->
	    <param-value>/WEB-INF/applicationContext.xml,classpath*:applicationContext.xml</param-value>
	</context-param>
	<!-- 启动服务器时实例化Listener对象,此时实例化Spring容器对象 -->
	<listener>
    	<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> -->
    	<listener-class>com.web.listener.CountLineListener</listener-class>
	</listener>
	<!-- 设置session超时时间 -->
	<session-config>
		<session-timeout>60</session-timeout>
	</session-config>
	<!-- 配置前端控制器 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<!--  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>-->
	</filter>
	
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
 

 

applicationContext.xml:

 

<!-- 让spring注入SessionFactory
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>	
	</bean>		
	 -->
	 
	<bean id="userDao" class="com.dao.impl.UserDaoImpl">
		<property name="mySessionFactory" ref="mySessionFactory"></property>
	</bean>
	
	<bean id="userService" class="com.service.impl.UserServiceImpl">
		<property name="userDao" ref="userDao"></property>
	</bean>
	
	<bean id="userAction" class="com.web.action.UserAction" scope="prototype">
		<property name="userService" ref="userService" />
	</bean>
	
	<bean id="editorAction" class="com.web.action.MyEditor" scope="prototype">
		<property name="userService" ref="userService" />
	</bean>
	
	<!-- 数据源->连接数据库 -->
	<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost/test"/>
		<property name="username" value="root"/>
		<property name="password" value="root"/>
	</bean>
	
	<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="myDataSource"/>
		<property name="mappingResources">
			<list>
				<value>com/entity/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<!-- 
			<value>hibernate.dialect=org.hibernate.dialect.MySQLDialect</value>
			 -->
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>
	
	<!-- 事物管理 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="mySessionFactory"></property>
	</bean>
	<!-- 配置事物通知 
		下面是Spring中Propagation类的事务属性详解: 
		REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。 
		SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。 
		MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。 
		REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。 
		NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 
		NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。 
		NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED"></tx:method>
			<tx:method name="del*" propagation="REQUIRED"></tx:method>
			<tx:method name="modi*" propagation="REQUIRED"></tx:method>
			<tx:method name="*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:pointcut id="serviceServiceMethods" expression="execution(* com.service.impl.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceServiceMethods"/>
	</aop:config>

 

然后编写数据访问层、业务层、实体类(仅用查询做测试_(:з」∠)_)

IUserDao.java:

 

package com.dao;

……
public interface IUserDao {
	/**
	 * 查询
	 * @param user
	 * @param pageSize
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<User> userFind(User user, int pageSize, int page) throws Exception;
	
}
 
UserDaoImpl.java:

 

 

package com.dao.impl;

……
public class UserDaoImpl extends HibernateDaoSupport implements IUserDao {
	
	private Logger log = Logger.getLogger(UserDaoImpl.class);
//	private HibernateTemplate ht; //不继承HibernateDaoSupport
	
//	public void setMySessionFactory(SessionFactory mySessionFactory) {
//		ht = new HibernateTemplate(mySessionFactory);
//	}
	
//	private SessionFactory sessionFactory;	
//	
//	public SessionFactory getSessionFactory() {
//		return sessionFactory;
//	}
	
	public void setMySessionFactory(SessionFactory mySessionFactory) {
		System.out.println("ლ(╹◡╹ლ)");
		super.setSessionFactory(mySessionFactory);
	}

	public List<User> userFind(User u, final int pageSize, final int page) {
		System.out.println("find 始め~");
		try {
			List<User> list = super.getHibernateTemplate().execute(new HibernateCallback<List<User>>() {
				public List<User> doInHibernate(Session session) throws HibernateException, SQLException {
					String sql = "from User";
//					List<Object> params = new ArrayList<Object>();
					Query query = session.createQuery(sql);
//					query.setParameter(1, "");
					query.setFirstResult((page - 1) * pageSize);
					query.setMaxResults(pageSize);
					return query.list();
				}
			});
			
			if(list.isEmpty())return null;
			return list;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
}
 

 

User.java:
package com.entity;

public class User {
	private Integer id;	
	private String username;	
	private String password;
	private String editor;
	……get、set……
}
 
User.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.entity"  >
	<class name="User" table="t_user" lazy="false">
		<id name="id" column="USER_ID">
			<generator class="native"></generator>
		</id>
		<property name="username" column="U_USERNAME" length="20" ></property>
		<property name="password" column="U_PASSWORD" length="20" ></property>
		<property name="editor" column="U_EDITOR" ></property>
	</class>	
</hibernate-mapping>
 
IUserService.java:
package com.service;

import java.io.File;
import java.util.List;

import com.entity.User;

public interface IUserService {
	public void add(User u) throws Exception;
	public void del(User u) throws Exception;
	public void modi(User u) throws Exception;
	public List<User> find(User user, int pageSize, int page) throws Exception;
	public int getTotalPage(User user, int pageSize) throws Exception;
	public void upLoad(File file, String fileName) throws Exception;
	public void delUpLoad(String fileName) throws Exception;
}
 
UserServiceImpl.java:
package com.service.impl;

import java.io.File;
import java.util.List;

import com.dao.IUserDao;
import com.entity.User;
import com.service.IUserService;

public class UserServiceImpl implements IUserService {
	
	private IUserDao userDao;	
	
	public UserServiceImpl() {
		super();
	}
	public IUserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}
	public List<User> find(User user, final int pageSize, final int page) throws Exception {
		return userDao.userFind(user, pageSize, page);
	}
}
 
页面请求处理什么的,strut2就不介绍了,写个测试类( ̄_, ̄ ),需要注意的是applicationContext.xml的路径√
public static void main(String[] args) throws Exception {
		
//		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		//WEB-INF下的路径
		BeanFactory ac = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
		IUserDao userDao = (IUserDao)ac.getBean("userDao");
		
		for(User u : userDao.userFind(null, 5, 1)){
			System.out.println("→_→ " + u.getUsername() + "\t" + u.getPassword());
		}
	}
 如果:

 
 
  • 大小: 26.9 KB
  • 大小: 11.2 KB
  • 大小: 20.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics