一:
myeclipse 傻瓜式的完成spring和hibernate的载入;
注意需要把lib里面的
asm-XX和
commons-collections-XX 低版本的删除掉,因为载入spring和hibernate的时候会装在2个不一样的版本,包冲突.
记得把dwr的包放进去
数据库用mysql.
CREATE TABLE `book` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(11) default NULL,
`isbm` varchar(11) default NULL,
`author` varchar(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=gbk;
id为自动增长
二:
完成上步后用hibernate的反向机制,完成数据库表的映射
如下:
AbstractBook.java
package com;
/**
* AbstractBook generated by MyEclipse Persistence Tools
*/
public abstract class AbstractBook implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private String isbm;
private String author;
// Constructors
/** default constructor */
public AbstractBook() {
}
/** full constructor */
public AbstractBook(String name, String isbm, String author) {
this.name = name;
this.isbm = isbm;
this.author = author;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbm() {
return this.isbm;
}
public void setIsbm(String isbm) {
this.isbm = isbm;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Book.java
package com;
// Generated by MyEclipse Persistence Tools
/**
* Book generated by MyEclipse Persistence Tools
*/
public class Book extends AbstractBook implements java.io.Serializable {
// Constructors
/** default constructor */
public Book() {
}
/** full constructor */
public Book(String name, String isbm, String author) {
super(name, isbm, author);
}
}
BookDAO.java
package com;
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;
/**
* Data access object (DAO) for domain model class Book.
*
* @see com.Book
* @author MyEclipse Persistence Tools
*/
public class BookDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(BookDAO.class);
protected void initDao() {
// do nothing
}
public void save(Book transientInstance) {
log.debug("saving Book instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException 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 (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Book findById(java.lang.Integer id) {
log.debug("getting Book instance with id: " + id);
try {
Book instance = (Book) getHibernateTemplate().get("com.Book", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Book instance) {
log.debug("finding Book 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 Book instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Book 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 findAll() {
log.debug("finding all Book instances");
try {
String queryString = "from Book";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException 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 (RuntimeException 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 (RuntimeException 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 (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static BookDAO getFromApplicationContext(ApplicationContext ctx) {
return (BookDAO) ctx.getBean("BookDAO");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Book.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="com.Book" table="book" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="11" />
</property>
<property name="isbm" type="java.lang.String">
<column name="isbm" length="11" />
</property>
<property name="author" type="java.lang.String">
<column name="author" length="11" />
</property>
</class>
</hibernate-mapping>
BookManageService.java 暴露给dwr使用的接口
package com;
import java.util.List;
public interface BookManageService {
public List<Book> getAllBooks();
public List<Book> getBookByName(String name);
public void updateBook(Book book);
public void addBook(Book book);
public void deleteBook(Integer id);
}
BookManageServiceImpl.java 接口的实现类
package com;
import java.util.List;
public class BookManageServiceImpl implements BookManageService {
private BookDAO bookDAO;
public BookDAO getBookDAO() {
return bookDAO;
}
public void setBookDAO(BookDAO bookDAO) {
this.bookDAO = bookDAO;
}
public void addBook(Book book) {
System.out.println("impl:"+book);
bookDAO.save(book);
}
public void deleteBook(Integer id) {
Book book = bookDAO.findById(id);
bookDAO.delete(book);
}
@SuppressWarnings("unchecked")
public List<Book> getAllBooks() {
return bookDAO.findAll();
}
@SuppressWarnings("unchecked")
public List<Book> getBookByName(String name) {
return bookDAO.findByProperty(name, name);
}
public void updateBook(Book book) {
bookDAO.attachDirty(book);
}
}
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="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/Book.hbm.xml</value>
</list>
</property>
</bean>
<bean id="BookDAO" class="com.BookDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="bookManageServiceTarget"
class="com.BookManageServiceImpl">
<property name="bookDAO">
<ref bean="BookDAO" />
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="bookManageService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager" />
<property name="target" ref="bookManageServiceTarget" />
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
</beans>
dwr.xml
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr//dwr20.dtd">
<dwr>
<allow>
<convert converter="bean" match="com.Book" />
<create creator="spring" javascript="BookManageService">
<param name="beanName" value="bookManageService" />
<include method="getAllBooks" />
<include method="getBookByName" />
<include method="updateBook" />
<include method="addBook" />
<include method="deleteBook" />
</create>
</allow>
</dwr>
index.jsp
<html>
<head>
<title>DWR test</title>
<script type='text/javascript' src='/shdwr/dwr/interface/BookManageService.js'></script>
<script type='text/javascript' src='/shdwr/dwr/engine.js'></script>
<script type='text/javascript' src='/shdwr/dwr/util.js'></script>
<script type="text/javascript">
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);
}
function reset(){
dwr.util.setValue("name", "");
dwr.util.setValue("isbm", "");
dwr.util.setValue("author", "");
}
</script>
</head>
<body onload="loadAllBooks()">
<div>
<h2>
Add book
</h2>
<table>
<tr>
<td>
Name:
</td>
<td>
<input type="text" id="name">
</td>
</tr>
<tr>
<td>
ISBN:
</td>
<td>
<input type="text" id="isbm">
</td>
</tr>
<tr>
<td>
Author:
</td>
<td>
<input type="text" id="author">
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" id="add" value="Add" onclick="addBook()">
<input type="reset" id="reset" value="reset" onclick="reset()">
<input type="button" id="update" value="Update"
onclick="updateBook()">
</td>
</tr>
</table>
</div>
<hr>
<div id="list">
<table border="1">
<thead>
<tr>
<th>
Name
</th>
<th>
ISBN
</th>
<th>
Author
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody id="booksBody">
<tr id="pattern" style="display: none;">
<td>
<span id="t_name"></span>
</td>
<td>
<span id="t_isbm"></span>
</td>
<td>
<span id="t_author"></span>
</td>
<td>
<span id="action"> <input id="edit" type="button"
value="Edit" onclick="editBook(this.id)" /> <input id="delete"
type="button" value="Delete" onclick="deleteBook(this.id)" />
</span>
</td>
</tr>
</tbody>
</table>
</div>
</body>