Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30480143
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2008-05-28 15:42:42

首先,建一个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. package edu.jlu.fuliang.domain;
  2. /** *//**
  3.  * Book generated by MyEclipse Persistence Tools
  4.  */
  5. public class Book implements java.io. {
  6.     // Fields
  7.     private  id;
  8.     private  name;
  9.     private  isbm;
  10.     private  author;
  11.     // Constructors
  12.     /** *//** default constructor */
  13.     public Book() {
  14.     }
  15.     /** *//** minimal constructor */
  16.     public Book( id,  name,  isbm) {
  17.         this.id = id;
  18.         this.name = name;
  19.         this.isbm = isbm;
  20.     }
  21.     /** *//** full constructor */
  22.     public Book( id,  name,  isbm,  author) {
  23.         this.id = id;
  24.         this.name = name;
  25.         this.isbm = isbm;
  26.         this.author = author;
  27.     }
  28.     // Property accessors
  29.     public  getId() {
  30.         return this.id;
  31.     }
  32.     public void setId( id) {
  33.         this.id = id;
  34.     }
  35.     public  getName() {
  36.         return this.name;
  37.     }
  38.     public void setName( name) {
  39.         this.name = name;
  40.     }
  41.     public  getIsbm() {
  42.         return this.isbm;
  43.     }
  44.     public void setIsbm( isbm) {
  45.         this.isbm = isbm;
  46.     }
  47.     public  getAuthor() {
  48.         return this.author;
  49.     }
  50.     public void setAuthor( author) {
  51.         this.author = author;
  52.     }
  53.     public  toString(){
  54.         return "[id=" + id + ",name=" + name + ",isbm=" + isbm + ",author=" + author + "]";
  55.     }
  56. }



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

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



Book.hbm.xml:

  1. "1.0" encoding="utf-8"?>
  2. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "">
  4.     <class name="edu.jlu.fuliang.domain.Book" table="BOOK" schema="CLASSICCARS">
  5.         "id" type="java.lang.Long">
  6.             "ID" />
  7.             class="identity" />
  8.         
  9.         "name" type="java.lang.String">
  10.             "NAME" length="20" not-null="true" />
  11.         
  12.         "isbm" type="java.lang.String">
  13.             "ISBM" length="20" not-null="true" unique="true" />
  14.         
  15.         "author" type="java.lang.String">
  16.             "AUTHOR" length="15" />
  17.         
  18.     class>


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

applicationContext-db.xml:


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



applicationContext-dao.xml:

  1. "1.0" encoding="UTF-8"?>
  2.     xmlns=""
  3.     xmlns:xsi=""
  4.     xsi:schemaLocation=" /spring-beans-2.0.xsd">
  5.     
  6.     "bookDAO" class="edu.jlu.fuliang.dao.BookDAO">
  7.         "sessionFactory">
  8.             "sessionFactory" />
  9.         
  10.     



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

edu.jlu.fuliang.service.BookManageService.java

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



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

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



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

applicationContext-service.xml:

  1. "1.0" encoding="UTF-8"?>
  2.     xmlns=""
  3.     xmlns:xsi=""
  4.     xsi:schemaLocation=" /spring-beans-2.0.xsd">
  5.     "bookManageServiceTarget" class="edu.jlu.fuliang.serviceImpl.BookManageServiceImpl">
  6.         "bookDAO">
  7.             "bookDAO"/>
  8.         
  9.     
  10.     "transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  11.         "sessionFactory" ref="sessionFactory"/>
  12.     
  13.     "bookManageService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
  14.         "transactionManager" ref="transactionManager"/>
  15.         "target" ref="bookManageServiceTarget"/>
  16.         "transactionAttributes">
  17.             
  18.                 "add*">PROPAGATION_REQUIRED
  19.                 "delete*">PROPAGATION_REQUIRED
  20.                 "update*">PROPAGATION_REQUIRED
  21.                 "get*">PROPAGATION_REQUIRED,readOnly
  22.             
  23.         
  24.     



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

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

web.xml:

  1. "1.0" encoding="UTF-8"?>
  2. "2.4" 
  3.     xmlns="" 
  4.     xmlns:xsi="" 
  5.     xsi:schemaLocation=
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  7.  
  8.      contextConfigLocation
  9.      classpath:applicationContext-*.xml
  10.  
  11.  
  12.      class>
  13.        org.springframework.web.context.ContextLoaderListener 
  14.      class>
  15.  
  16.  
  17.      dwr-invoker
  18.      class>org.directwebremoting.servlet.DwrServletclass>
  19.      
  20.          debug
  21.          true
  22.      
  23.  
  24.  
  25.      dwr-invoker
  26.      /dwr/*
  27.  



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

  1.     
  2.         
  3.         
  4.             
  5.             
  6.             
  7.             
  8.             
  9.             
  10.         
  11.    



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

  1. DWR test
  2.     
  3.     
  4.     
  5.     
  6.         var bookCache = ...{};
  7.         var currentBook = null;
  8.         
  9.         function loadAllBooks(){
  10.             BookManageService.getAllBooks(handleGetAllBooks,handleGetAllBooksError);
  11.         }
  12.         function handleGetAllBooks(books){
  13.             dwr.util.removeAllRows("booksBody",{ filter:function(tr) ...{
  14.       return (tr.id != "pattern");
  15.       }});
  16.             var book,id;
  17.             for(var i = 0; i < books.length; i++){
  18.                 book = books[i];
  19.                 id = book.id;
  20.             
  21.                 dwr.util.cloneNode("pattern", { idSuffix:id });
  22.                 dwr.util.setValue("t_name" + id, book.name);
  23.                 dwr.util.setValue("t_isbm" + id, book.isbm);
  24.                 dwr.util.setValue("t_author" + id,book.author);
  25.                $("pattern" + id).style.display = "block";
  26.                bookCache[id] = book;
  27.             }
  28.         }
  29.         function handleGetAllBooksError(msg){
  30.             alert("Error: " + msg);
  31.         }
  32.         
  33.         function addBook(){
  34.             var book = ...{name:null,isbm:null,author:null};
  35.             dwr.util.getValues(book);
  36.             dwr.engine.beginBatch();
  37.                  BookManageService.addBook(book);
  38.                  loadAllBooks();
  39.               dwr.engine.endBatch();
  40.         }
  41.         
  42.         function editBook(btId){
  43.             currentBook = bookCache[btId.substring(4)];
  44.             dwr.util.setValues(currentBook);
  45.         }
  46.         
  47.         function updateBook(){
  48.             var book = {id:null,name:null,isbm:null,author:null}; 
  49.             dwr.util.getValues(book);
  50.             book.id = currentBook.id;
  51.             BookManageService.updateBook(book,handleUpdateBook,handleUpdateBookError);
  52.         }
  53.         
  54.         function handleUpdateBook(){
  55.             alert("Update book successfully!");
  56.             loadAllBooks();
  57.         }
  58.         
  59.         function handleUpdateBookError(msg){
  60.             alert("Error: " + msg);
  61.         }
  62.         
  63.         function deleteBook(btId){
  64.             var i = confirm("Are you sure to delete the book?");
  65.             if(i == true)
  66.                 BookManageService.deleteBook(btId.substring(6),handleDeleteBook,handleDeleteBookError);
  67.         }
  68.         
  69.         function handleDeleteBook(){
  70.           alert("The book has been delete successfully!");
  71.           loadAllBooks();
  72.         }
  73.         
  74.         function handleDeleteBookError(msg){
  75.           alert("Error: " + msg);
  76.         }
  77.     
  78.     
  79.         

    Add book

  80.         
  81.             
  82.               
  83.             
  84.             
  85.               
  86.               
  87.              
  88.             
  89.             
  90.                
  91.                
  92.            
  93.            
  94.                
  95.                  
  96.                  
  97.                
  98.            
  99.        
  100. Name:
    ISBN:
    Author:
  101.     
  •     
  •     
  •         
  •           
  •               
  •                   Name
  •                   ISBN
  •                   Author
  •                   Action
  •               
  •           
  •           
  •               
  •                   
  •                     
  •                   
  •                   
  •                     
  •                   
  •                   
  •                     
  •                   
  •                   
  •                     
  •                         
  •                       
  •                     
  •                   
  •               
  •           
  •         
  •     


  • 这样我们就完成了Spring+Hibernate+DWR的整合,我们可以在一个页面完成CURD操作了.

    阅读(2348) | 评论(1) | 转发(0) |
    给主人留下些什么吧!~~

    chinaunix网友2008-07-01 22:02:50

    垃圾东西