spring+hibernate+dwr小结

spring+hibenate+dwr是个不错的组合,特别是DWR是J2EE中AJAX中不错的选择来的,最近在读李刚的<<基于j2ee的AJAX宝典>>,
发现的确是本好书,下面小结下spring+hiberante+dwr使用时的一些步骤
   比如一篇BLOG,可以拥有多个评论,这是典型的一对多关系了,先看model层

1 model层

blog.java
public class Blog
{
    private int id;
    private String title;
    private String content;
 private Date addTime;
 
 private Set<Comment> comments = new HashSet<Comment>();
 
 public Blog()
 {
 }
  
//get,set等方法

comment.java

public class Comment
{
    private int id;
    private String user;
    private String email;
 private String url;
 private String content;
 private Date addTime;

    private Blog  blog;
//....get.set等方法

2 hbm文件
  
blog.hbm.xml:
 <class name="Blog" table="blog_table">
  <id name="id">
   <generator class="identity"/>
  </id>
  <property name="title"/>
  <property name="content" type="text"/>
  <property name="addTime"/>
  <set name="comments"  inverse="true">
   <key column="blog_id"/>
   <one-to-many class="Comment"/>
  </set>
 </class>

comment.hbm.xml:
<class name="Comment" table="comment_table">
  <id name="id">
   <generator class="identity"/>
  </id>
  <property name="user"/>
  <property name="email"/>
  <property name="url"/>
  <property name="content"/>
  <property name="addTime"/>
  <many-to-one name="blog" column="blog_id" not-null="true"/>
 </class>

3  DAO层
    blogdao.java (节省篇幅,举例子而已)


public interface BlogDao
{
 /**
  * 根据主键加载Blog
  * @param id 需要加载的Blog ID
  * @return 加载的Blog
  */
    Blog get(int id);

 /**
  * 保存Blog
  * @param b 需要保存的Blog
  */
    void save(Blog b);

public interface BlogDao
{
 /**
  * 根据主键加载Blog
  * @param id 需要加载的Blog ID
  * @return 加载的Blog
  */
    Blog get(int id);

 /**
  * 保存Blog
  * @param b 需要保存的Blog
  */
    void save(Blog b);


。。。。。。
}


  blogdaoimpl.java (BLOGADAO接口的实现类)


public class BlogDaoHibernate extends HibernateDaoSupport
 implements BlogDao
{
 //每页显示的消息数
 private int pageSize;
 //每页的消息数通过依赖注入管理
 public void setPageSize(int pageSize)
 {
  this.pageSize = pageSize;
 }

 /**
  * 根据主键加载Blog
  * @param id 需要加载的Blog ID
  * @return 加载的Blog
  */
    public Blog get(int id)
 {
  return (Blog)getHibernateTemplate().get(Blog.class , new Integer(id));
 }

 /**
  * 保存Blog
  * @param b 需要保存的Blog
  */
    public void save(Blog b)
 {
  getHibernateTemplate().save(b);
 }

...........................

4  业务逻辑层
  业务逻辑层接口
    blogmanager.java
public interface BlogManager
{
 /**
  * 创建一条Blog文章
  * @param title Blog文章的标题
  * @param content Blog文章的内容
  * @return 新创建Blog文章的主键,如果创建失败,返回-1。
  */
 int createBlog(String title , String content)
  throws BlogException;

.......................

}

   业务逻辑层实现blogmanagerimpl.java


public class BlogManagerImpl implements BlogManager
{
 private BlogDao blogDao;
 private CommentDao commentDao;

 public void setBlogDao(BlogDao blogDao)
 {
  this.blogDao = blogDao;
 }
 public void setCommentDao(CommentDao commentDao)
 {
  this.commentDao = commentDao;
 }


 /**
  * 创建一条Blog文章
  * @param title Blog文章的标题
  * @param content Blog文章的内容
  * @return 新创建Blog文章的主键,如果创建失败,返回-1。
  */
 public int createBlog(String title , String content)
  throws BlogException
 {
  try
  {
   Blog b = new Blog();
   b.setTitle(title);
   b.setContent(content);
   b.setAddTime(new Date());
   blogDao.save(b);
   return b.getId();
  }
  catch (Exception e)
  {
   e.printStackTrace();
   throw new BlogException("保存Blog文章出错");
  }
 }

5  配置业务逻辑组件
   applicationcontext.xml
 

<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.xsd">

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3309/blog"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="user" value="root"/>
        <property name="password" value="123456789"/>
        <property name="maxPoolSize" value="40"/>
        <property name="minPoolSize" value="1"/>
        <property name="initialPoolSize" value="1"/>
        <property name="maxIdleTime" value="20"/>
    </bean>


    <!--定义了Hibernate的SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
    <value>Blog.hbm.xml</value>
    <value>Comment.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.jdbc.batch_size">20</prop>
            </props>
        </property>
    </bean>

    <bean id="blogDao" class="org.yeeku.dao.impl.BlogDaoHibernate">
        <property name="sessionFactory" ref="sessionFactory"/>
        <property name="pageSize" value="3"/>
    </bean>

    <bean id="commentDao" class="org.yeeku.dao.impl.CommentDaoHibernate">
        <property name="sessionFactory" ref="sessionFactory"/>
        <property name="pageSize" value="3"/>
    </bean>


    <bean id="blogManager" class="org.yeeku.service.impl.BlogManagerImpl">
        <property name="blogDao" ref="blogDao"/>
        <property name="commentDao" ref="commentDao"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
     <!--  事务拦截器bean需要依赖注入一个事务管理器 -->
        <property name="transactionManager" ref="transactionManager"/>
     <property name="transactionAttributes">
      <!--  下面定义事务传播属性-->
      <props>
       <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
       <prop key="*">PROPAGATION_REQUIRED</prop>
      </props>
     </property>
 </bean>

    <!-- 定义BeanNameAutoProxyCreator-->
    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
     <!--  指定对满足哪些bean name的bean自动生成业务代理 -->
     <property name="beanNames">
            <!--  下面是所有需要自动创建事务代理的bean-->
            <list>
    <value>blogManager</value>
            </list>
            <!--  此处可增加其他需要自动创建事务代理的bean-->
     </property>
        <!--  下面定义BeanNameAutoProxyCreator所需的事务拦截器-->
        <property name="interceptorNames">
            <list>
                <!-- 此处可增加其他新的Interceptor -->
                <value>transactionInterceptor</value>
            </list>
        </property>
    </bean>

 5  初始化 dwr
  web.xml
   

<?xml version="1.0" encoding="GBK"?>

<web-app 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"
    version="2.4">

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
 </context-param>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- 配置DWR的核心Servlet -->
 <servlet>
  <!-- 指定DWR核心Servlet的名字 -->
  <servlet-name>dwr-invoker</servlet-name>
  <!-- 指定DWR核心Servlet的实现类 -->
  <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
  <!--  指定DWR核心Servlet处于调试状态 -->
  <init-param>
   <param-name>debug</param-name>
   <param-value>true</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <!-- 指定核心Servlet的URL映射 -->
 <servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <!-- 指定核心Servlet映射的URL -->
  <url-pattern>/leedwr/*</url-pattern>
 </servlet-mapping>

</web-app>

6 DWR.XML
 

<dwr>
 <allow>
  <create creator="spring" javascript="bm">
   <param name="beanName" value="blogManager"/>
   <include method="createComment"/>
   <include method="createBlog"/>
   <include method="getAllBlogByPage"/>
   <include method="getCommentsByBlogAndPage"/>
   <include method="getBlog"/>
   <include method="getNewestBlog"/>
  </create>
  <convert converter="bean" match="org.yeeku.vo.CommentBean"/>
  <convert converter="bean" match="org.yeeku.vo.BlogBean"/>

 </allow>
</dwr
   其中配置了javascript对象bm,该对象由dwr通过spring容器中的blogmanager创建,还定义了两个javabean,可以被转化为javascript对象
7 客户端调用

  比如添加BLOG的功能:
.

/创建新Blog文章
function addBlog()
{
 var blogTitle = $("blogTitle").value;
 var blogContent = $("blogContent").value;

 if (blogTitle == null || blogTitle == "" || blogContent == null || blogContent == "")
 {
  alert("新增Blog文章时,必须指定文章标题,文章内容");
 }
 else
 {
  bm.createBlog(blogTitle , blogContent , addBlogCb);
 }
}

//创建新Blog文章的回调函数
function addBlogCb(data)
{
 if (typeof data != "number" || data < 1)
 {
  alert("添加文章失败");
 }
 else
 {
  $("blogTitle").value = "";
  $("blogContent").value = ""
  alert("添加文章成功");
  window.close();
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值