首先,建一个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:
- package edu.jlu.fuliang.domain;
- /** *//**
- * Book generated by MyEclipse Persistence Tools
- */
- public class Book implements java.io. {
- // Fields
- private id;
- private name;
- private isbm;
- private author;
- // Constructors
- /** *//** default constructor */
- public Book() {
- }
- /** *//** minimal constructor */
- public Book( id, name, isbm) {
- this.id = id;
- this.name = name;
- this.isbm = isbm;
- }
- /** *//** full constructor */
- public Book( id, name, isbm, author) {
- this.id = id;
- this.name = name;
- this.isbm = isbm;
- this.author = author;
- }
- // Property accessors
- public getId() {
- return this.id;
- }
- public void setId( id) {
- this.id = id;
- }
- public getName() {
- return this.name;
- }
- public void setName( name) {
- this.name = name;
- }
- public getIsbm() {
- return this.isbm;
- }
- public void setIsbm( isbm) {
- this.isbm = isbm;
- }
- public getAuthor() {
- return this.author;
- }
- public void setAuthor( author) {
- this.author = author;
- }
- public toString(){
- return "[id=" + id + ",name=" + name + ",isbm=" + isbm + ",author=" + author + "]";
- }
- }
edu.jlu.fuliang.dao.BookDAO.java:
- package edu.jlu.fuliang.dao;
- import java.util.;
- import org.apache.commons.logging.;
- import org.apache.commons.logging.;
- import org.hibernate.LockMode;
- import org.springframework.context.ApplicationContext;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import edu.jlu.fuliang.domain.Book;
- /** *//**
- * Data access object (DAO) for domain model class Book.
- *
- * @see edu.jlu.fuliang.domain.Book
- * @author MyEclipse Persistence Tools
- */
- public class BookDAO extends HibernateDaoSupport ...{
- private static final log = .getLog(BookDAO.class);
- // property constants
- public static final NAME = "name";
- public static final ISBM = "isbm";
- public static final AUTHOR = "author";
- protected void initDao() ...{
- // do nothing
- }
- public void save(Book transientInstance) ...{
- log.debug("saving Book instance");
- try ...{
- getHibernateTemplate().save(transientInstance);
- log.debug("save successful");
- } catch ( re) ...{
- log.error("save failed", re);
- throw re;
- }
- }
- public void delete(Book persistentInstance) ...{
- log.debug("deleting Book instance");
- try ...{
- getHibernateTemplate().delete(persistentInstance);
- log.debug("delete successful");
- } catch ( re) ...{
- log.error("delete failed", re);
- throw re;
- }
- }
- public Book findById(java.lang. id) ...{
- log.debug("getting Book instance with id: " + id);
- try ...{
- Book instance = (Book) getHibernateTemplate().get(
- "edu.jlu.fuliang.domain.Book", id);
- return instance;
- } catch ( re) ...{
- log.error("get failed", re);
- throw re;
- }
- }
- public findByExample(Book instance) ...{
- log.debug("finding Book instance by example");
- try ...{
- results = getHibernateTemplate().findByExample(instance);
- log.debug("find by example successful, result size: "
- + results.size());
- return results;
- } catch ( re) ...{
- log.error("find by example failed", re);
- throw re;
- }
- }
- public findByProperty( propertyName, value) ...{
- log.debug("finding Book instance with property: " + propertyName
- + ", value: " + value);
- try ...{
- queryString = "from Book as model where model."
- + propertyName + "= ?";
- return getHibernateTemplate().find(queryString, value);
- } catch ( re) ...{
- log.error("find by property name failed", re);
- throw re;
- }
- }
- public findByName( name) ...{
- return findByProperty(NAME, name);
- }
- public findByIsbm( isbm) ...{
- return findByProperty(ISBM, isbm);
- }
- public findByAuthor( author) ...{
- return findByProperty(AUTHOR, author);
- }
- public findAll() ...{
- log.debug("finding all Book instances");
- try ...{
- queryString = "from Book";
- return getHibernateTemplate().find(queryString);
- } catch ( re) ...{
- log.error("find all failed", re);
- throw re;
- }
- }
- public Book merge(Book detachedInstance) ...{
- log.debug("merging Book instance");
- try ...{
- Book result = (Book) getHibernateTemplate().merge(detachedInstance);
- log.debug("merge successful");
- return result;
- } catch ( re) ...{
- log.error("merge failed", re);
- throw re;
- }
- }
- public void attachDirty(Book instance) ...{
- log.debug("attaching dirty Book instance");
- try ...{
- getHibernateTemplate().saveOrUpdate(instance);
- log.debug("attach successful");
- } catch ( re) ...{
- log.error("attach failed", re);
- throw re;
- }
- }
- public void attachClean(Book instance) ...{
- log.debug("attaching clean Book instance");
- try ...{
- getHibernateTemplate().lock(instance, LockMode.NONE);
- log.debug("attach successful");
- } catch ( re) ...{
- log.error("attach failed", re);
- throw re;
- }
- }
- public static BookDAO getFromApplicationContext(ApplicationContext ctx) ...{
- return (BookDAO) ctx.getBean("BookDAO");
- }
- }
Book.hbm.xml:
- "1.0" encoding="utf-8"?>
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "">
-
-
- <class name="edu.jlu.fuliang.domain.Book" table="BOOK" schema="CLASSICCARS">
- "id" type="java.lang.Long">
- "ID" />
- class="identity" />
-
- "name" type="java.lang.String">
- "NAME" length="20" not-null="true" />
-
- "isbm" type="java.lang.String">
- "ISBM" length="20" not-null="true" unique="true" />
-
- "author" type="java.lang.String">
- "AUTHOR" length="15" />
-
- class>
-
下面我们配置一下Spring,我们把applicationContext.xml分成了三个,分别是applicationContext-db.xml,applicationContext-dao.xml,applicationContext-service.我们看看如何配置:
applicationContext-db.xml:
- "1.0" encoding="UTF-8"?>
-
- xmlns=""
- xmlns:xsi=""
- xsi:schemaLocation=" /spring-beans-2.0.xsd">
- "dataSource"
- class="org.apache.commons.dbcp.BasicDataSource">
- "driverClassName"
- value="org.apache.derby.jdbc.ClientDriver">
-
- "url"
- value="jdbc:derby://localhost:1527/myeclipse;create=true">
-
- "username" value="classiccars">
- "password" value="myeclipse">
-
- "sessionFactory"
- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- "dataSource">
-
["dataSource" /> ]
-
- "hibernateProperties">
-
- "hibernate.dialect">
- org.hibernate.dialect.DerbyDialect
-
- "hibernate.show_sql">
- true
-
-
-
- "mappingResources">
-
- edujlufuliangdomainBook.hbm.xml
-
-
-
applicationContext-dao.xml:
- "1.0" encoding="UTF-8"?>
-
- xmlns=""
- xmlns:xsi=""
- xsi:schemaLocation=" /spring-beans-2.0.xsd">
-
- "bookDAO" class="edu.jlu.fuliang.dao.BookDAO">
- "sessionFactory">
-
["sessionFactory" /> ]
-
-
接下来我们来写我们的Service层:
edu.jlu.fuliang.service.BookManageService.java
- package edu.jlu.fuliang.service;
- import java.util.;
- import edu.jlu.fuliang.domain.Book;
- public interface BookManageService {
- public <Book> getAllBooks();
- public <Book> getBookByName( name);
- public void updateBook(Book book);
- public void addBook(Book book);
- public void deleteBook(long id);
- }
edu.jlu.fuliang.service.impl.BookManageServiceImpl.java:
- package edu.jlu.fuliang.serviceImpl;
- import java.util.;
- import org.apache.commons.logging.;
- import org.apache.commons.logging.;
- import edu.jlu.fuliang.dao.BookDAO;
- import edu.jlu.fuliang.domain.Book;
- import edu.jlu.fuliang.service.BookManageService;
- public class BookManageServiceImpl implements BookManageService{
- private static final log = .getLog(BookManageServiceImpl.class);
- private BookDAO bookDAO;
- @Override
- public void addBook(Book book) {
- bookDAO.save(book);
- }
- @Override
- public void deleteBook(long id) {
- Book book = bookDAO.findById(id);
- bookDAO.delete(book);
- }
- @Override
- public <Book> getAllBooks() {
- return bookDAO.findAll();
- }
- @Override
- public <Book> getBookByName( name) {
- return bookDAO.findByName(name);
- }
- @Override
- public void updateBook(Book book) {
- log.info(book);
- bookDAO.attachDirty(book);
- }
- public BookDAO getBookDAO() {
- return bookDAO;
- }
- public void setBookDAO(BookDAO bookDAO) {
- this.bookDAO = bookDAO;
- }
- }
然后我们来配置Service和事务:
applicationContext-service.xml:
- "1.0" encoding="UTF-8"?>
-
- xmlns=""
- xmlns:xsi=""
- xsi:schemaLocation=" /spring-beans-2.0.xsd">
- "bookManageServiceTarget" class="edu.jlu.fuliang.serviceImpl.BookManageServiceImpl">
- "bookDAO">
-
["bookDAO"/> ]
-
-
- "transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- "sessionFactory" ref="sessionFactory"/>
-
- "bookManageService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
- "transactionManager" ref="transactionManager"/>
- "target" ref="bookManageServiceTarget"/>
- "transactionAttributes">
-
- "add*">PROPAGATION_REQUIRED
- "delete*">PROPAGATION_REQUIRED
- "update*">PROPAGATION_REQUIRED
- "get*">PROPAGATION_REQUIRED,readOnly
-
-
-
最后我们来把dwr整合进来:
我们在web.xml添加ContextLoaderListener来加载applicationContext-db.xml,applicationContext-dao.xm,applicationContext-service.xml,以及配置DwrServlet:
web.xml:
- "1.0" encoding="UTF-8"?>
- "2.4"
- xmlns=""
- xmlns:xsi=""
- xsi:schemaLocation="
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
-
- contextConfigLocation
- classpath:applicationContext-*.xml
-
-
- class>
- org.springframework.web.context.ContextLoaderListener
- class>
-
-
- dwr-invoker
- class>org.directwebremoting.servlet.DwrServletclass>
-
- debug
- true
-
-
-
- dwr-invoker
- /dwr/*
-
-
在dwr.xml中配制bean的创建方式,类型转换,以及Service要暴露的接口:
最后,我们编写jsp页面index.jsp:
-
- DWR test
-
-
-
-
- var bookCache = ...{};
- var currentBook = null;
-
- function loadAllBooks(){
- BookManageService.getAllBooks(handleGetAllBooks,handleGetAllBooksError);
- }
- function handleGetAllBooks(books){
- dwr.util.removeAllRows("booksBody",{ filter:function(tr) ...{
- return (tr.id != "pattern");
- }});
- var book,id;
- for(var i = 0; i < books.length; i++){
- book = books[i];
- id = book.id;
-
- dwr.util.cloneNode("pattern", { idSuffix:id });
- dwr.util.setValue("t_name" + id, book.name);
- dwr.util.setValue("t_isbm" + id, book.isbm);
- dwr.util.setValue("t_author" + id,book.author);
- $("pattern" + id).style.display = "block";
- bookCache[id] = book;
- }
- }
- function handleGetAllBooksError(msg){
- alert("Error: " + msg);
- }
-
- function addBook(){
- var book = ...{name:null,isbm:null,author:null};
- dwr.util.getValues(book);
- dwr.engine.beginBatch();
- BookManageService.addBook(book);
- loadAllBooks();
- dwr.engine.endBatch();
- }
-
- function editBook(btId){
- currentBook = bookCache[btId.substring(4)];
- dwr.util.setValues(currentBook);
- }
-
- function updateBook(){
- var book = {id:null,name:null,isbm:null,author:null};
- dwr.util.getValues(book);
- book.id = currentBook.id;
- BookManageService.updateBook(book,handleUpdateBook,handleUpdateBookError);
- }
-
- function handleUpdateBook(){
- alert("Update book successfully!");
- loadAllBooks();
- }
-
- function handleUpdateBookError(msg){
- alert("Error: " + msg);
- }
-
- function deleteBook(btId){
- var i = confirm("Are you sure to delete the book?");
- if(i == true)
- BookManageService.deleteBook(btId.substring(6),handleDeleteBook,handleDeleteBookError);
- }
-
- function handleDeleteBook(){
- alert("The book has been delete successfully!");
- loadAllBooks();
- }
-
- function handleDeleteBookError(msg){
- alert("Error: " + msg);
- }
-
-
-
-
-
-
-
-
这样我们就完成了Spring+Hibernate+DWR的整合,我们可以在一个页面完成CURD操作了.
阅读(2348) | 评论(1) | 转发(0) |