程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 一個簡單的hibernate與spring集成

一個簡單的hibernate與spring集成

編輯:關於JAVA

下面介紹一下hibernate與spring的集成,這兩個框架的集成關鍵在於 applicationContext.xml文件的配置,其實很簡單的,但需要注意的是,導入包 時一定選擇導入到webroot/web-inf/lib目錄中,而且hibernate一般要在spring 之前導入,因為集成時要用到sessionFactory類,

一、初始化工作:新建一個項目,如(ssh),在此項目中導入對hibernate的支持 ,新建一個表sstest表,有字段id,username,password,id為主健和自動增1

二、對新建的數據表進行hibernate進行映射,打開myhibernate視圖,右擊你 sstest表->選hibernate revers engineering選項,然後把Sstest.hbm.xml 文件映射到hibernateDao包中,同時選中工具 hibernate mapping file...,  java data object....., java data access object dao...選項,先中這幾個 文件就可以產生下列幾個.java文件:BaseHibernateDAO. ,HibernateSessionFactory ,IBaseHibernateDAO, Sstest,SstestDAO,最後你對 你的代碼進行測試,測試成功,進行下一步

三、在項目中導入對spring的支持,在導入項目後不但要自動產生 applicationContext.xml,而且在這個文件裡會出現下面的內容:

<bean id="sessionFactory" 

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 <property name="configLocation" 

value="classpath:hibernate.cfg.xml"> 
 </property>
</bean>

這就是為什麼要先要導入hibernate的原因

四、若你對spring的ioc比較熟,你可以直接進入下一步,如果不是很了解, 那麼你可以寫一個比較簡單的例子測試一下看是否成功,必竟框架和在一起,所 以小心點好,不然在以後出了有問題不好找

五、進入myeclipse hibernate視圖下,在新的包(如springDao)中重新對 sstest表進行映射,這次映射要注意的就是:打開hibernate reverse engineering對話框中復選按鈕java data access object(dao)(hibernate 3 only)下,dao type 不是選basic dao選項,而是選spring dao選項,當你映射 成功後,就會出現Sstest.java, SstestDAO.java, Sstest.hbm.xml幾個文件, 你可以寫一個類進行測試,如:

springdaotest.java

package org.test;
import org.springframework.context.ApplicationContext;
import 

org.springframework.context.support.ClassPathXmlApplicationContext;
import springDao.Sstest;
import springDao.SstestDAO;
public class SpringDaoTest {
public static void main(String a[]){
 ApplicationContext cont = new ClassPathXmlApplicationContext

("applicationContext.xml");
 SstestDAO s = (SstestDAO) cont.getBean("SstestDAO");
  SstestDAO s = (SstestDAO) cont.getBean("SstestDAOProxy");
 Sstest st = new Sstest();
 st.setUsername("spring");
 st.setPassword("spring");
 s.save(st); 
}
}

六、由於映射了兩次,所以你要在hibernate.cfg.xml文件中,把原來映射的 文件注解掉:

<mapping resource="hibernateDao/Sstest.hbm.xml" />

因為現在已有一行這樣的代碼:

<mapping resource="springDao/Sstest.hbm.xml" />

七、實現hibernate spring 代理,加上下面的代碼即可:

<bean id="transactionManager" 

class="org.springframework.orm.hibernate3.HibernateTransactionManager"

>
 <property name="sessionFactory">
  <ref local="sessionFactory"/>
 </property>
</bean>
<bean id="SstestDAOProxy" 

class="org.springframework.transaction.interceptor.TransactionProxyFac

toryBean">
 <property name="proxyTargetClass">
  <value>true</value>
 </property>
 <property name="transactionManager">
  <ref bean="transactionManager"/>
 </property>
 <property name="target">
  <ref local="SstestDAO"/>
 </property>
 <property name="transactionAttributes">
  <props>
  <prop key="*">PROPAGATION_REQUIRED</prop>
  </props>
 </property>
</bean>

在進行測試,測試時,還是用原來的類,只需把SstestDAO s = (SstestDAO) cont.getBean("SstestDAO");變成

SstestDAO s = (SstestDAO) cont.getBean("SstestDAOProxy");這次的 bean是用的代碼類實現

下面是完整的代碼:

在這個實例中hibernate包中的文件BaseHibernateDAO. ,HibernateSessionFactory ,IBaseHibernateDAO, Sstest,SstestDAO, Sstest.hbm.xml ,和在一個簡單的struts,hibernate例子以及 struts,hibernate集成中的文件是一樣的,代碼一樣,下面是一些其它代碼:

applicationContext.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"
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>
<!-- spring dao -->
<bean id="SstestDAO" class="springDao.SstestDAO">
 <property name="sessionFactory">
  <ref bean="sessionFactory"/>
 </property>
</bean>
<!-- hibernate 3 事務代理 -->
<bean id="transactionManager" 

class="org.springframework.orm.hibernate3.HibernateTransactionManager"

>
 <property name="sessionFactory">
  <ref local="sessionFactory"/>
 </property>
</bean>
<bean id="SstestDAOProxy" 

class="org.springframework.transaction.interceptor.TransactionProxyFac

toryBean">
 <property name="proxyTargetClass">
  <value>true</value>
 </property>
 <property name="transactionManager">
  <ref bean="transactionManager"/>
 </property>
 <property name="target">
  <ref local="SstestDAO"/>
 </property>
 <property name="transactionAttributes">
  <props>
  <prop key="*">PROPAGATION_REQUIRED</prop>
  </props>
 </property>
</bean>
</beans>

測試類:SpringDaoTest.java

package org.test;
import org.springframework.context.ApplicationContext;
import 

org.springframework.context.support.ClassPathXmlApplicationContext;
import springDao.Sstest;
import springDao.SstestDAO;
public class SpringDaoTest {
public static void main(String a[]){
 ApplicationContext cont = new ClassPathXmlApplicationContext

("applicationContext.xml");
 //SstestDAO s = (SstestDAO) cont.getBean("SstestDAO");
 //代理類
 SstestDAO s = (SstestDAO) cont.getBean("SstestDAOProxy");
 Sstest st = new Sstest();
 st.setUsername("spring");
 st.setPassword("spring");
 s.save(st); 
}
}

Sstest.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">
<!--
  Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
  <class name="springDao.Sstest" table="sstest" schema="dbo" 

catalog="manager">
    <id name="id" type="java.lang.Integer">
      <column name="id" />
      <generator class="increment" />
    </id>
    <property name="username" type="java.lang.String">
      <column name="username" length="10" />
    </property>
    <property name="password" type="java.lang.String">
      <column name="password" length="20" />
    </property>
  </class>
</hibernate-mapping>

SstestDAO.java

package springDao;
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;
public class SstestDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(SstestDAO.class);
// property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
protected void initDao() {
 // do nothing
}
public void save(Sstest transientInstance) {
 log.debug("saving Sstest instance");
 System.out.println("Ok");
 try {
  getHibernateTemplate().save(transientInstance);
  log.debug("save successful");
  System.out.print("save Ok");
 } catch (RuntimeException re) {
  log.error("save failed", re);
  throw re;
 }
}
public void delete(Sstest persistentInstance) {
 log.debug("deleting Sstest instance");
 try {
  getHibernateTemplate().delete(persistentInstance);
  log.debug("delete successful");
 } catch (RuntimeException re) {
  log.error("delete failed", re);
  throw re;
 }
}
public Sstest findById(java.lang.Integer id) {
 log.debug("getting Sstest instance with id: " + id);
 try {
  Sstest instance = (Sstest) getHibernateTemplate().get(
   "springDao.Sstest", id);
  return instance;
 } catch (RuntimeException re) {
  log.error("get failed", re);

  throw re;
 }
}
public List findByExample(Sstest instance) {
 log.debug("finding Sstest 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 Sstest instance with property: " + propertyName
  + ", value: " + value);
 try {
  String queryString = "from Sstest 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 findByUsername(Object username) {
 return findByProperty(USERNAME, username);
}
public List findByPassword(Object password) {
 return findByProperty(PASSWORD, password);
}
public List findAll() {
 log.debug("finding all Sstest instances");
 try {
  String queryString = "from Sstest";
  return getHibernateTemplate().find(queryString);
 } catch (RuntimeException re) {
  log.error("find all failed", re);
  throw re;
 }
}
public Sstest merge(Sstest detachedInstance) {
 log.debug("merging Sstest instance");
 try {
  Sstest result = (Sstest) getHibernateTemplate().merge(
   detachedInstance);
  log.debug("merge successful");
  return result;
 } catch (RuntimeException re) {
  log.error("merge failed", re);
  throw re;
 }
}
public void attachDirty(Sstest instance) {
 log.debug("attaching dirty Sstest instance");
 try {
  getHibernateTemplate().saveOrUpdate(instance);
  log.debug("attach successful");
 } catch (RuntimeException re) {
  log.error("attach failed", re);
  throw re;
 }
}
public void attachClean(Sstest instance) {
 log.debug("attaching clean Sstest instance");
 try {
  getHibernateTemplate().lock(instance, LockMode.NONE);
  log.debug("attach successful");
 } catch (RuntimeException re) {
  log.error("attach failed", re);
  throw re;
 }
}
public static SstestDAO getFromApplicationContext(ApplicationContext 

ctx) {
 return (SstestDAO) ctx.getBean("SstestDAO");
}
}

Sstest.java

package springDao;
public class Sstest implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
// Constructors
/** default constructor */
public Sstest() {
}
/** full constructor */
public Sstest(String username, String password) {
 this.username = username;
 this.password = password;
}
// Property accessors
public Integer getId() {
 return this.id;
}
public void setId(Integer id) {
 this.id = id;
}
public String getUsername() {
 return this.username;
}
public void setUsername(String username) {
 this.username = username;
}
public String getPassword() {
 return this.password;
}
public void setPassword(String password) {
 this.password = password;
}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-

3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.          --

>
<hibernate-configuration>
<session-factory>
 <property name="connection.username">sa</property>
 <property name="connection.url">
  jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=manager
 </property>
 <property name="dialect">
  org.hibernate.dialect.SQLServerDialect
 </property>
 <property name="myeclipse.connection.profile">
  com.microsoft.jdbc.sqlserver.SQLServerDriver
 </property>
 <property name="connection.password">wq</property>
 <property name="connection.driver_class">
  com.microsoft.jdbc.sqlserver.SQLServerDriver
 </property>
 <!-- <mapping resource="hibernateDao/Sstest.hbm.xml" /> --

>
 <!-- 使用springdao -->
 <mapping resource="springDao/Sstest.hbm.xml" />
</session-factory>
</hibernate-configuration>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved