论坛首页 Java企业应用论坛

Spring+hibernate+DWR整合

浏览 8818 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-10-08  
首先,建一个web project,然后添加对hibernate和spring的支持,我们使用的是hibernate3.1和spring2.0,然后导入dwr.jar和commons-pool-1.3.jar(不知道myeclipse怎么搞的,添加Spring功能支持的时候就有了commons-dbcp.jar,居然没有其依赖的commons-pool-x.jar,只好单独添加了,另外,需要将Spring2.0 AOP Liberaries里的asm2.2.3.jar删除,因为好像和Hiberate中的生成代理用的asm.jar冲突,我把Spring2.0 AOP Liberaries排到最后仍然有冲突,所以只好删掉了,不知道大家遇到过这种情况么)。
我们使用myeclise自带的Derby数据库,在里面建一个表BOOK:
ID bigint primary key,autoincrement
NAME varchar(20)
ISBM varchar(20)
AUTHOR varchar(15)
然后利用myeclipse的hibernate反向工程生成领域模型:Book.java, DAO:BookDAO.jar, Book 的映射文件Book.hbm.xml:
生成的代码及配置文件如下:
Book.java:

  1.  
  2. package edu.jlu.fuliang.domain;
  3. /** *//**
  4.  * Book generated by MyEclipse Persistence Tools
  5.  */
  6.  
  7. public class Book implements java.io.Serializable {
  8.  
  9.     // Fields
  10.  
  11.     private Long id;
  12.     private String name;
  13.     private String isbm;
  14.     private String author;
  15.  
  16.     // Constructors
  17.  
  18.     /** *//** default constructor */
  19.     public Book() {
  20.     }
  21.  
  22.     /** *//** minimal constructor */
  23.     public Book(Long id, String name, String isbm) {
  24.         this.id = id;
  25.         this.name = name;
  26.         this.isbm = isbm;
  27.     }
  28.  
  29.     /** *//** full constructor */
  30.     public Book(Long id, String name, String isbm, String author) {
  31.         this.id = id;
  32.         this.name = name;
  33.         this.isbm = isbm;
  34.         this.author = author;
  35.     }
  36.  
  37.     // Property accessors
  38.  
  39.     public Long getId() {
  40.         return this.id;
  41.     }
  42.  
  43.     public void setId(Long id) {
  44.         this.id = id;
  45.     }
  46.  
  47.     public String getName() {
  48.         return this.name;
  49.     }
  50.  
  51.     public void setName(String name) {
  52.         this.name = name;
  53.     }
  54.  
  55.     public String getIsbm() {
  56.         return this.isbm;
  57.     }
  58.  
  59.     public void setIsbm(String isbm) {
  60.         this.isbm = isbm;
  61.     }
  62.  
  63.     public String getAuthor() {
  64.         return this.author;
  65.     }
  66.  
  67.     public void setAuthor(String author) {
  68.         this.author = author;
  69.     }
  70.     public String toString(){
  71.         return "[id=" + id + ",name=" + name + ",isbm=" + isbm + ",author=" + author + "]";
  72.     }
  73. }


edu.jlu.fuliang.dao.BookDAO.java:

  1. package edu.jlu.fuliang.dao;
  2.  
  3. import java.util.List;
  4. import org.apache.commons.logging.Log;
  5. import org.apache.commons.logging.LogFactory;
  6. import org.hibernate.LockMode;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
  9.  
  10. import edu.jlu.fuliang.domain.Book;
  11.  
  12. /** *//**
  13.  * Data access object (DAO) for domain model class Book.
  14.  * 
  15.  * @see edu.jlu.fuliang.domain.Book
  16.  * @author MyEclipse Persistence Tools
  17.  */
  18.  
  19. public class BookDAO extends HibernateDaoSupport ...{
  20.     private static final Log log = LogFactory.getLog(BookDAO.class);
  21.     // property constants
  22.     public static final String NAME = "name";
  23.     public static final String ISBM = "isbm";
  24.     public static final String AUTHOR = "author";
  25.  
  26.     protected void initDao() ...{
  27.         // do nothing
  28.     }
  29.  
  30.     public void save(Book transientInstance) ...{
  31.         log.debug("saving Book instance");
  32.         try ...{
  33.             getHibernateTemplate().save(transientInstance);
  34.             log.debug("save successful");
  35.         } catch (RuntimeException re) ...{
  36.             log.error("save failed", re);
  37.             throw re;
  38.         }
  39.     }
  40.  
  41.     public void delete(Book persistentInstance) ...{
  42.         log.debug("deleting Book instance");
  43.         try ...{
  44.             getHibernateTemplate().delete(persistentInstance);
  45.             log.debug("delete successful");
  46.         } catch (RuntimeException re) ...{
  47.             log.error("delete failed", re);
  48.             throw re;
  49.         }
  50.     }
  51.  
  52.     public Book findById(java.lang.Long id) ...{
  53.         log.debug("getting Book instance with id: " + id);
  54.         try ...{
  55.             Book instance = (Book) getHibernateTemplate().get(
  56.                     "edu.jlu.fuliang.domain.Book", id);
  57.             return instance;
  58.         } catch (RuntimeException re) ...{
  59.             log.error("get failed", re);
  60.             throw re;
  61.         }
  62.     }
  63.  
  64.     public List findByExample(Book instance) ...{
  65.         log.debug("finding Book instance by example");
  66.         try ...{
  67.             List results = getHibernateTemplate().findByExample(instance);
  68.             log.debug("find by example successful, result size: "
  69.                     + results.size());
  70.             return results;
  71.         } catch (RuntimeException re) ...{
  72.             log.error("find by example failed", re);
  73.             throw re;
  74.         }
  75.     }
  76.  
  77.     public List findByProperty(String propertyName, Object value) ...{
  78.         log.debug("finding Book instance with property: " + propertyName
  79.                 + ", value: " + value);
  80.         try ...{
  81.             String queryString = "from Book as model where model."
  82.                     + propertyName + "= ?";
  83.             return getHibernateTemplate().find(queryString, value);
  84.         } catch (RuntimeException re) ...{
  85.             log.error("find by property name failed", re);
  86.             throw re;
  87.         }
  88.     }
  89.  
  90.     public List findByName(Object name) ...{
  91.         return findByProperty(NAME, name);
  92.     }
  93.  
  94.     public List findByIsbm(Object isbm) ...{
  95.         return findByProperty(ISBM, isbm);
  96.     }
  97.  
  98.     public List findByAuthor(Object author) ...{
  99.         return findByProperty(AUTHOR, author);
  100.     }
  101.  
  102.     public List findAll() ...{
  103.         log.debug("finding all Book instances");
  104.         try ...{
  105.             String queryString = "from Book";
  106.             return getHibernateTemplate().find(queryString);
  107.         } catch (RuntimeException re) ...{
  108.             log.error("find all failed", re);
  109.             throw re;
  110.         }
  111.     }
  112.  
  113.     public Book merge(Book detachedInstance) ...{
  114.         log.debug("merging Book instance");
  115.         try ...{
  116.             Book result = (Book) getHibernateTemplate().merge(detachedInstance);
  117.             log.debug("merge successful");
  118.             return result;
  119.         } catch (RuntimeException re) ...{
  120.             log.error("merge failed", re);
  121.             throw re;
  122.         }
  123.     }
  124.  
  125.     public void attachDirty(Book instance) ...{
  126.         log.debug("attaching dirty Book instance");
  127.         try ...{
  128.             getHibernateTemplate().saveOrUpdate(instance);
  129.             log.debug("attach successful");
  130.         } catch (RuntimeException re) ...{
  131.             log.error("attach failed", re);
  132.             throw re;
  133.         }
  134.     }
  135.  
  136.     public void attachClean(Book instance) ...{
  137.         log.debug("attaching clean Book instance");
  138.         try ...{
  139.             getHibernateTemplate().lock(instance, LockMode.NONE);
  140.             log.debug("attach successful");
  141.         } catch (RuntimeException re) ...{
  142.             log.error("attach failed", re);
  143.             throw re;
  144.         }
  145.     }
  146.  
  147.     public static BookDAO getFromApplicationContext(ApplicationContext ctx) ...{
  148.         return (BookDAO) ctx.getBean("BookDAO");
  149.     }
  150. }


Book.hbm.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!-- 
  5.     Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8.     <class name="edu.jlu.fuliang.domain.Book" table="BOOK" schema="CLASSICCARS">
  9.         <id name="id" type="java.lang.Long">
  10.             <column name="ID" />
  11.             <generator class="identity" />
  12.         </id>
  13.         <property name="name" type="java.lang.String">
  14.             <column name="NAME" length="20" not-null="true" />
  15.         </property>
  16.         <property name="isbm" type="java.lang.String">
  17.             <column name="ISBM" length="20" not-null="true" unique="true" />
  18.         </property>
  19.         <property name="author" type="java.lang.String">
  20.             <column name="AUTHOR" length="15" />
  21.         </property>
  22.     </class>
  23. </hibernate-mapping>

下面我们配置一下Spring,我们把applicationContext.xml分成了三个,分别是applicationContext-db.xml,applicationContext-dao.xml,applicationContext-service.我们看看如何配置:

applicationContext-db.xml:


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3.     xmlns="http://www.springframework.org/schema/beans"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  6.  
  7.     <bean id="dataSource"
  8.         class="org.apache.commons.dbcp.BasicDataSource">
  9.         <property name="driverClassName"
  10.             value="org.apache.derby.jdbc.ClientDriver">
  11.         </property>
  12.         <property name="url"
  13.             value="jdbc:derby://localhost:1527/myeclipse;create=true">
  14.         </property>
  15.         <property name="username" value="classiccars"></property>
  16.         <property name="password" value="myeclipse"></property>
  17.     </bean>
  18.     <bean id="sessionFactory"
  19.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  20.         <property name="dataSource">
  21.             <ref bean="dataSource" />
  22.         </property>
  23.         <property name="hibernateProperties">
  24.             <props>
  25.                 <prop key="hibernate.dialect">
  26.                     org.hibernate.dialect.DerbyDialect
  27.                 </prop>
  28.                 <prop key="hibernate.show_sql">
  29.                    true
  30.                 </prop>
  31.             </props>
  32.         </property>
  33.         <property name="mappingResources">
  34.             <list>
  35.                 <value>edujlufuliangdomainBook.hbm.xml</value>
  36.             </list>
  37.         </property>
  38.     </bean>
  39. </beans>


applicationContext-dao.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3.     xmlns="http://www.springframework.org/schema/beans"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  6.     
  7.     <bean id="bookDAO" class="edu.jlu.fuliang.dao.BookDAO">
  8.         <property name="sessionFactory">
  9.             <ref bean="sessionFactory" />
  10.         </property>
  11.     </bean>
  12. </beans>


接下来我们来写我们的Service层:

edu.jlu.fuliang.service.BookManageService.java

  1. package edu.jlu.fuliang.service;
  2. import java.util.List;
  3.  
  4. import edu.jlu.fuliang.domain.Book;
  5.  
  6. public interface BookManageService {
  7.     public List<Book> getAllBooks();
  8.     public List<Book> getBookByName(String name);
  9.     public void updateBook(Book book);
  10.     public void addBook(Book book);
  11.     public void deleteBook(long id);
  12. }


edu.jlu.fuliang.service.impl.BookManageServiceImpl.java:

  1. package edu.jlu.fuliang.serviceImpl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.apache.commons.logging.Log;
  6. import org.apache.commons.logging.LogFactory;
  7.  
  8. import edu.jlu.fuliang.dao.BookDAO;
  9. import edu.jlu.fuliang.domain.Book;
  10. import edu.jlu.fuliang.service.BookManageService;
  11.  
  12. public class BookManageServiceImpl implements BookManageService{
  13.     private static final Log log = LogFactory.getLog(BookManageServiceImpl.class);
  14.     private BookDAO bookDAO;
  15.     @Override
  16.     public void addBook(Book book) {
  17.         bookDAO.save(book);
  18.     }
  19.  
  20.     @Override
  21.     public void deleteBook(long id) {
  22.         Book book = bookDAO.findById(id);
  23.         bookDAO.delete(book);
  24.     }
  25.  
  26.     @Override
  27.     public List<Book> getAllBooks() {
  28.         return bookDAO.findAll();
  29.     }
  30.  
  31.     @Override
  32.     public List<Book> getBookByName(String name) {
  33.         return bookDAO.findByName(name);
  34.     }
  35.  
  36.     @Override
  37.     public void updateBook(Book book) {
  38.         log.info(book);
  39.         bookDAO.attachDirty(book);
  40.     }
  41.  
  42.     public BookDAO getBookDAO() {
  43.         return bookDAO;
  44.     }
  45.  
  46.     public void setBookDAO(BookDAO bookDAO) {
  47.         this.bookDAO = bookDAO;
  48.     }
  49. }


然后我们来配置Service和事务:

applicationContext-service.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3.     xmlns="http://www.springframework.org/schema/beans"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  6.  
  7.     <bean id="bookManageServiceTarget" class="edu.jlu.fuliang.serviceImpl.BookManageServiceImpl">
  8.         <property name="bookDAO">
  9.             <ref bean="bookDAO"/>
  10.         </property>
  11.     </bean>
  12.     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  13.         <property name="sessionFactory" ref="sessionFactory"/>
  14.     </bean>
  15.     <bean id="bookManageService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
  16.         <property name="transactionManager" ref="transactionManager"/>
  17.         <property name="target" ref="bookManageServiceTarget"/>
  18.         <property name="transactionAttributes">
  19.             <props>
  20.                 <prop key="add*">PROPAGATION_REQUIRED</prop>
  21.                 <prop key="delete*">PROPAGATION_REQUIRED</prop>
  22.                 <prop key="update*">PROPAGATION_REQUIRED</prop>
  23.                 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
  24.             </props>
  25.         </property>
  26.     </bean>
  27. </beans>


最后我们来把dwr整合进来:

我们在web.xml添加ContextLoaderListener来加载applicationContext-db.xml,applicationContext-dao.xm,applicationContext-service.xml,以及配置DwrServlet:

web.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.4" 
  3.     xmlns="http://java.sun.com/xml/ns/j2ee" 
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  7.  <context-param>
  8.      <param-name>contextConfigLocation</param-name>
  9.      <param-value>classpath:applicationContext-*.xml</param-value>
  10.  </context-param>
  11.  <listener>
  12.      <listener-class>
  13.        org.springframework.web.context.ContextLoaderListener 
  14.      </listener-class>
  15.  </listener>
  16.  <servlet>
  17.      <servlet-name>dwr-invoker</servlet-name>
  18.      <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  19.      <init-param>
  20.          <param-name>debug</param-name>
  21.          <param-value>true</param-value>
  22.      </init-param>
  23.  </servlet>
  24.  <servlet-mapping>
  25.      <servlet-name>dwr-invoker</servlet-name>
  26.      <url-pattern>/dwr/*</url-pattern>
  27.  </servlet-mapping>
  28. </web-app>


在dwr.xml中配制bean的创建方式,类型转换,以及Service要暴露的接口:

  1. <dwr>
  2.     <allow>
  3.         <convert converter="bean" match="edu.jlu.fuliang.domain.Book"/>
  4.         <create creator="spring" javascript="BookManageService" >
  5.             <param name="beanName" value="bookManageService"/>
  6.             <include method="getAllBooks"/>
  7.             <include method="getBookByName"/>
  8.             <include method="updateBook"/>
  9.             <include method="addBook"/>
  10.             <include method="deleteBook"/>
  11.         </create>
  12.    </allow>
  13. </dwr>


最后,我们编写jsp页面index.jsp:

  1. <html>
  2. <head><title>DWR test</title>
  3.     <script type='text/javascript' src='/DWRTest/dwr/interface/BookManageService.js'></script>
  4.     <script type='text/javascript' src='/DWRTest/dwr/engine.js'></script>
  5.     <script type='text/javascript' src='/DWRTest/dwr/util.js'></script>
  6.  
  7.     <script type="text/javascript">
  8.         var
   发表时间:2007-10-09  
把项目打个包。。或者把帖子写进word贴个附件吧。。几个配置文件有问题被过滤了
0 请登录后投票
   发表时间:2007-10-09  
对啊!!!发一个压缩包吧!
0 请登录后投票
   发表时间:2007-10-09  
貌似是转载我在csdn的blog, 还有我的包名
edu.jlu.fuliang...,呵呵
我嫌维护两个Blog费劲,没往这里的Blog里滕,谢谢转载.
我给大家一个压缩的吧.
  • DWRTest.rar (461.2 KB)
  • 描述: 用MyEclipse部署之后,需要把lib目录下的asm-2.2.3.jar去掉
  • 下载次数: 926
0 请登录后投票
   发表时间:2007-10-09  
页面再加上webwork
那应该就比较爽了。
0 请登录后投票
   发表时间:2007-10-09  
linginfanta 写道
页面再加上webwork
那应该就比较爽了。

我也写了一篇整合Ajax+Struts2+Spring+Hibernate的,Struts2的Ajax底层使用了Dwr和Dojo,所以整合dwr可以省掉.工程也一并传上.
  • Struts2Test.rar (906.5 KB)
  • 描述: Ajax+Struts2+Spring+Hibernate整合, 用MyEclipse部署后,去掉lib目录下的asm-2.2.3.jar文件
  • 下载次数: 1195
0 请登录后投票
   发表时间:2007-10-09  
楼主贴的看的不太清晰,如果有需要的话可以到Spring+Hibernate+DWR整合查看.
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics