首先,建一个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:
1package edu.jlu.fuliang.domain;
2/** *//** *//** *//**
3 * Book generated by MyEclipse Persistence Tools
4 */
5
6public class Book implements java.io.Serializable {
7
8 // Fields
9
10 private Long id;
11 private String name;
12 private String isbm;
13 private String author;
14
15 // Constructors
16
17 /** *//** *//** *//** default constructor */
18 public Book() {
19 }
20
21 /** *//** *//** *//** minimal constructor */
22 public Book(Long id, String name, String isbm) {
23 this.id = id;
24 this.name = name;
25 this.isbm = isbm;
26 }
27
28 /** *//** *//** *//** full constructor */
29 public Book(Long id, String name, String isbm, String author) {
30 this.id = id;
31 this.name = name;
32 this.isbm = isbm;
33 this.author = author;
34 }
35
36 // Property accessors
37
38 public Long getId() {
39 return this.id;
40 }
41
42 public void setId(Long id) {
43 this.id = id;
44 }
45
46 public String getName() {
47 return this.name;
48 }
49
50 public void setName(String name) {
51 this.name = name;
52 }
53
54 public String getIsbm() {
55 return this.isbm;
56 }
57
58 public void setIsbm(String isbm) {
59 this.isbm = isbm;
60 }
61
62 public String getAuthor() {
63 return this.author;
64 }
65
66 public void setAuthor(String author) {
67 this.author = author;
68 }
69 public String toString(){
70 return "[id=" + id + ",name=" + name + ",isbm=" + isbm + ",author=" + author + "]";
71 }
72}
73
edu.jlu.fuliang.dao.BookDAO.java:
1package edu.jlu.fuliang.dao;
2
3import java.util.List;
4import org.apache.commons.logging.Log;
5import org.apache.commons.logging.LogFactory;
6import org.hibernate.LockMode;
7import org.springframework.context.ApplicationContext;
8import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
9
10import 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
19public 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}
151
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>
24
下面我们配置一下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>
13
接下来我们来写我们的Service层:
edu.jlu.fuliang.service.BookManageService.java
1package edu.jlu.fuliang.service;
2import java.util.List;
3
4import edu.jlu.fuliang.domain.Book;
5
6public 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}
13
edu.jlu.fuliang.service.impl.BookManageServiceImpl.java:
1package edu.jlu.fuliang.serviceImpl;
2
3import java.util.List;
4
5import org.apache.commons.logging.Log;
6import org.apache.commons.logging.LogFactory;
7
8import edu.jlu.fuliang.dao.BookDAO;
9import edu.jlu.fuliang.domain.Book;
10import edu.jlu.fuliang.service.BookManageService;
11
12public 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}
50
然后我们来配置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>
29
在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>
14
最后,我们编写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 bookCache = {};
9 var currentBook = null;
10
11 function loadAllBooks(){
12 BookManageService.getAllBooks(handleGetAllBooks,handleGetAllBooksError);
13 }
14 function handleGetAllBooks(books){
15 dwr.util.removeAllRows("booksBody",{ filter:function(tr) {
16 return (tr.id != "pattern");
17 }});
18
19 var book,id;
20 for(var i = 0; i < books.length; i++){
21 book = books[i];
22 id = book.id;
23
24 dwr.util.cloneNode("pattern", { idSuffix:id });
25 dwr.util.setValue("t_name" + id, book.name);
26 dwr.util.setValue("t_isbm" + id, book.isbm);
27 dwr.util.setValue("t_author" + id,book.author);
28 $("pattern" + id).style.display = "block";
29 bookCache[id] = book;
30 }
31 }
32 function handleGetAllBooksError(msg){
33 alert("Error: " + msg);
34 }
35
36 function addBook(){
37 var book = {name:null,isbm:null,author:null};
38 dwr.util.getValues(book);
39 dwr.engine.beginBatch();
40 BookManageService.addBook(book);
41 loadAllBooks();
42 dwr.engine.endBatch();
43 }
44
45 function editBook(btId){
46 currentBook = bookCache[btId.substring(4)];
47 dwr.util.setValues(currentBook);
48 }
49
50 function updateBook(){
51 var book = {id:null,name:null,isbm:null,author:null};
52 dwr.util.getValues(book);
53 book.id = currentBook.id;
54 BookManageService.updateBook(book,handleUpdateBook,handleUpdateBookError);
55 }
56
57 function handleUpdateBook(){
58 alert("Update book successfully!");
59 loadAllBooks();
60 }
61
62 function handleUpdateBookError(msg){
63 alert("Error: " + msg);
64 }
65
66 function deleteBook(btId){
67 var i = confirm("Are you sure to delete the book?");
68 if(i == true)
69 BookManageService.deleteBook(btId.substring(6),handleDeleteBook,handleDeleteBookError);
70 }
71
72 function handleDeleteBook(){
73 alert("The book has been delete successfully!");
74 loadAllBooks();
75 }
76
77 function handleDeleteBookError(msg){
78 alert("Error: " + msg);
79 }
80 </script>
81</head>
82
83<body onload="loadAllBooks()">
84 <div>
85 <h2>Add book</h2>
86 <table>
87 <tr>
88 <td>Name:</td><td><input type="text" id="name"></td>
89 </tr>
90 <tr>
91 <td>ISBN:</td>
92 <td><input type="text" id="isbm"></td>
93 </tr>
94
95 <tr>
96 <td>Author:</td>
97 <td><input type="text" id="author"></td>
98 </tr>
99 <tr>
100 <td colspan="2">
101 <input type="button" id="add" value="Add" onclick="addBook()">
102 <input type="button" id="update" value="Update" onclick="updateBook()">
103 </td>
104 </tr>
105 </table>
106 </div>
107 <hr>
108 <div id="list">
109 <table border="1">
110 <thead>
111 <tr>
112 <th>Name</th>
113 <th>ISBN</th>
114 <th>Author</th>
115 <th>Action</th>
116 </tr>
117 </thead>
118 <tbody id="booksBody">
119 <tr id="pattern" style="display:none;">
120 <td>
121 <span id="t_name"></span>
122 </td>
123 <td>
124 <span id="t_isbm"></span>
125 </td>
126 <td>
127 <span id="t_author"></span>
128 </td>
129 <td>
130 <span id="action">
131 <input id="edit" type="button" value="Edit" onclick="editBook(this.id)"/>
132 <input id="delete" type="button" value="Delete" onclick="deleteBook(this.id)"/>
133 </span>
134 </td>
135 </tr>
136 </tbody>
137 </table>
138 </div>
139</body>
140
posted on 2007-10-12 11:17
冰封的爱 阅读(308)
评论(0) 编辑 收藏 所属分类:
J2EE