`

spring整合hibernate实例

阅读更多
新建web工程,添加spring功能,添加hibernate功能
然后反向工程,生成spring整合hibernate的DAO和表格对应的类。
工程的目录结构如:


JavaBean :
package com.qdu.sun.BO;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.qud.sun.hibernate.IUserDAO;
import com.qud.sun.hibernate.User;
public class Register {
	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
    public void insert()
    {
    	ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    	IUserDAO dao = (IUserDAO)ctx.getBean("UserDAO");
    	User user = new User();
    	user.setPassword(password);
    	user.setName(username);
    	dao.save(user);
    }
}

生成的USerdao:
package com.qud.sun.hibernate;
// default package

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 	* A data access object (DAO) providing persistence and search support for User entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see .User
  * @author MyEclipse Persistence Tools 
 */

public class UserDAO extends HibernateDaoSupport implements IUserDAO  {
    private static final Log log = LogFactory.getLog(UserDAO.class);
	//property constants
	public static final String NAME = "name";
	public static final String PASSWORD = "password";



	protected void initDao() {
		//do nothing
	}
    
    public void save(User transientInstance) {
        log.debug("saving User instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(User persistentInstance) {
        log.debug("deleting User instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public User findById( java.lang.Integer id) {
        log.debug("getting User instance with id: " + id);
        try {
            User instance = (User) getHibernateTemplate()
                    .get("User", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    public List findByExample(User instance) {
        log.debug("finding User instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding User instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from User as model where model." 
         						+ propertyName + "= ?";
		 return getHibernateTemplate().find(queryString, value);
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByName(Object name
	) {
		return findByProperty(NAME, name
		);
	}
	
	public List findByPassword(Object password
	) {
		return findByProperty(PASSWORD, password
		);
	}
	

	public List findAll() {
		log.debug("finding all User instances");
		try {
			String queryString = "from User";
		 	return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    public User merge(User detachedInstance) {
        log.debug("merging User instance");
        try {
            User result = (User) getHibernateTemplate()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(User instance) {
        log.debug("attaching dirty User instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(User instance) {
        log.debug("attaching clean User instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
    	return (UserDAO) ctx.getBean("UserDAO");
	}

	public List findByUsername(Object username) {
		return null;
	}
}

index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>注册</title>
		<meta http-equiv="content-type" content="text/html; charset=GBK">
	</head>
	<script type="text/javascript">
// 验证输入不为空的脚本代码
function checkForm(form) {
if(form.username.value == "") {
alert("用户名不能为空!");
form.username.focus();
return false;
}
if(form.password.value == "") {
alert("密码不能为空!");
form.password.focus();
return false;
}
return true;
}
</script>
	<body>
		请输入注册信息
		<br>
		<form action="insert.jsp" method="post"
			onsubmit="return checkForm(this);">
			用户名:
			<input type="text" name="username">
			<br>
			密码:
			<input type="password" name="password">
			<br>
			<input type="submit" value="注册" name="submit1">
			<input type="reset" value="重置" name="reset1">
		</form>
	</body>
</html>

insert.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'MyJsp.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <jsp:useBean id="regist" class="com.qdu.sun.BO.Register" scope="session" />
    <jsp:setProperty name="regist" property="*" />
    <% 
      regist.insert();
    %>
    
  </body>
</html>

spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">


	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation"
			value="classpath:hibernate.cfg.xml">
		</property>
	</bean>
	<bean id="UserDAO" class="com.qud.sun.hibernate.UserDAO">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean></beans>


然后部署到tomcat上运行tomcat,地址栏中输入访问index.html的URL。

但是,执行完,查看数据时,却发现数据并没有保存进去。这是为啥?不是hibernate的错误,hibernate框架确实执行了对应的插入操作,但是hibernate的操作必须在事务中执行才能够得到正确的结果,而dao类中,只定义了hibernate的操作,并没有涉及到事务提交。

因此,在实际开发中,必须使用spring框架来实现事务的自动提交。有两种方式,一种是用spring1.2的事务代理类,另一种使用spring 2.0中的AOP声明式配置。本实例采用第二种。
只需修改spring的配置文件即可:
在applicationContext.xml中添加如下内容:
<!-- 声明一个 Hibernate 3 的 事务管理器供代理类自动管理事务用 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>
	<aop:config>
		<!-- 切入点指明了在执行dao.StudentDAO的所有方法时产生事务拦截操作 -->
		<aop:pointcut id="daoMethods"
			expression="execution(* com.qdu.sun.hibernate.UserDAO.*(..))" />
		<!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" />
	</aop:config>
	<!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 指定哪些方法需要加入事务,这里懒惰一下全部加入,可以使用通配符来
				只加入需要的方法 -->
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics