知道美河 | 上传资料 | VIP申请 | 精品课程 | 资料搜索 | 问题反馈 | 会员手册 | 积分消费 | 积分充值 | 帐号保护
美河学习学习在线赞助VIP

美河学习在线(主站) eimhe.com

 找回密码
 建立账号
查看: 5764|回复: 3

[分享] 感谢 adamed 那个小程序已经完成通过了谢谢

[复制链接]
发表于 2007-1-25 10:05:51 | 显示全部楼层 |阅读模式
这是一个一对多的程序:struts+hibernate

在adamed的指点下做好了.拿来给大家分享一下.

SQL:create table forum(
id int primary key auto_increment,
name varchar(40)
);



create table topic(
id int primary key auto_increment,
title varchar(50),
cont varchar(500),
author varchar(40),
time time,
forumid int
);

create table reponse(
id int primary key auto_increment,
cont varchar(500),
author varchar(40),
time time,
topicid int
);

alter table topic add constraint fk_id foreign key (forumid) references forum(id);

alter table reponse add constraint fk_tid foreign key (topicid) references topic(id);
直接用myEclipse映射不用动并生成DAO.

FORUMDAO:
package org.hiber;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

/**
* Data access object (DAO) for domain model class Forum.
* @see org.hiber.Forum
* @author MyEclipse - Hibernate Tools
*/
public class ForumDAO extends BaseHibernateDAO {

    private static final Log log = LogFactory.getLog(ForumDAO.class);

        //property constants
        public static final String NAME = "name";

   
    public void save(Forum transientInstance) {
        log.debug("saving Forum instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
   
        public void delete(Forum persistentInstance) {
        log.debug("deleting Forum instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
   
    public Forum findById( java.lang.Integer id) {
        log.debug("getting Forum instance with id: " + id);
        try {
                Transaction tx = getSession().beginTransaction();
            Forum instance = (Forum) getSession()
                    .get("org.hiber.Forum", id);
            tx.commit();
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
   
   
    public List findByExample(Forum instance) {
        log.debug("finding Forum instance by example");
        try {
            List results = getSession()
                    .createCriteria("org.hiber.Forum")
                    .add(Example.create(instance))
            .list();
            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 Forum instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Forum as model where model."
                                                         + propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
                 queryObject.setParameter(0, value);
                 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
        }

        public List findByName(Object name) {
                return findByProperty(NAME, name);
        }
       
    public Forum merge(Forum detachedInstance) {
        log.debug("merging Forum instance");
        try {
            Forum result = (Forum) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Forum instance) {
        log.debug("attaching dirty Forum instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
    public void attachClean(Forum instance) {
        log.debug("attaching clean Forum instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
   
   
    public List getForumList(){
           
            String hql="from Forum as f";
            List list=new ArrayList();
            list=getSession().createQuery(hql).list();
            return list;
           
    }
      
}

TopicDAO:
package org.hiber;

import java.util.*;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

/**
* Data access object (DAO) for domain model class Topic.
* @see org.hiber.Topic
* @author MyEclipse - Hibernate Tools
*/
public class TopicDAO extends BaseHibernateDAO {

    private static final Log log = LogFactory.getLog(TopicDAO.class);

        //property constants
        public static final String TITLE = "title";
        public static final String CONT = "cont";
        public static final String AUTHOR = "author";

   
    public void save(Topic transientInstance) {
        log.debug("saving Topic instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
   
        public void delete(Topic persistentInstance) {
        log.debug("deleting Topic instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
   
    public Topic findById( java.lang.Integer id) {
        log.debug("getting Topic instance with id: " + id);
        try {
            Topic instance = (Topic) getSession()
                    .get("org.hiber.Topic", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
   
   
    public List findByExample(Topic instance) {
        log.debug("finding Topic instance by example");
        try {
            List results = getSession()
                    .createCriteria("org.hiber.Topic")
                    .add(Example.create(instance))
            .list();
            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 Topic instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Topic as model where model."
                                                         + propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
                 queryObject.setParameter(0, value);
                 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
        }

        public List findByTitle(Object title) {
                return findByProperty(TITLE, title);
        }
       
        public List findByCont(Object cont) {
                return findByProperty(CONT, cont);
        }
       
        public List findByAuthor(Object author) {
                return findByProperty(AUTHOR, author);
        }
       
    public Topic merge(Topic detachedInstance) {
        log.debug("merging Topic instance");
        try {
            Topic result = (Topic) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Topic instance) {
        log.debug("attaching dirty Topic instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
    public void attachClean(Topic instance) {
        log.debug("attaching clean Topic instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
   
    public Set getTopic(Integer id){
               
                List list=new ArrayList();
                Set set=new HashSet();
                try{
                        ForumDAO forumDao = new ForumDAO();
                        set=forumDao.findById(id).getTopics();
                        //list=(List)forumDao.findById(id).getTopics();
                }catch(Exception e){
                        e.printStackTrace();
                }
                return set;
        }
   
   
   
}

ReponseDAO:
package org.hiber;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

/**
* Data access object (DAO) for domain model class Reponse.
* @see org.hiber.Reponse
* @author MyEclipse - Hibernate Tools
*/
public class ReponseDAO extends BaseHibernateDAO {

    private static final Log log = LogFactory.getLog(ReponseDAO.class);

        //property constants
        public static final String CONT = "cont";
        public static final String AUTHOR = "author";

   
    public void save(Reponse transientInstance) {
        log.debug("saving Reponse instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
   
        public void delete(Reponse persistentInstance) {
        log.debug("deleting Reponse instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
   
    public Reponse findById( java.lang.Integer id) {
        log.debug("getting Reponse instance with id: " + id);
        try {
            Reponse instance = (Reponse) getSession()
                    .get("org.hiber.Reponse", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
   
   
    public List findByExample(Reponse instance) {
        log.debug("finding Reponse instance by example");
        try {
            List results = getSession()
                    .createCriteria("org.hiber.Reponse")
                    .add(Example.create(instance))
            .list();
            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 Reponse instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Reponse as model where model."
                                                         + propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
                 queryObject.setParameter(0, value);
                 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
        }

        public List findByCont(Object cont) {
                return findByProperty(CONT, cont);
        }
       
        public List findByAuthor(Object author) {
                return findByProperty(AUTHOR, author);
        }
       
    public Reponse merge(Reponse detachedInstance) {
        log.debug("merging Reponse instance");
        try {
            Reponse result = (Reponse) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Reponse instance) {
        log.debug("attaching dirty Reponse instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
    public void attachClean(Reponse instance) {
        log.debug("attaching clean Reponse instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
   
   
    public Set getReponseList(int id){
           
            List list=new ArrayList();
            Set set=new HashSet();
            TopicDAO topDao=new TopicDAO();
            set=topDao.findById(id).getReponses();
            return set;
           
    }
}

ShowAction:显示FORUM:

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package org.bbs.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.bbs.struts.form.ShowForm;
import org.hiber.ForumDAO;

/**
* MyEclipse Struts
* Creation date: 01-24-2007
*
* XDoclet definition:
* @struts.action path="/show" name="showForm" input="/show.jsp" scope="request" validate="true"
*/
public class ShowAction extends Action {
        /*
         * Generated Methods
         */

        /**
         * Method execute
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @return ActionForward
         */
        public ActionForward execute(ActionMapping mapping, ActionForm form,
                        HttpServletRequest request, HttpServletResponse response) {
                ShowForm showForm = (ShowForm) form;// TODO Auto-generated method stub
                ForumDAO forumDao=new ForumDAO();
                List forumList=forumDao.getForumList();
               
                request.setAttribute("forumList", forumList);
                return mapping.findForward("showForum");
               
        }
}

ShowTopicAction:显示TOPIC:

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package org.bbs.struts.action;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hiber.TopicDAO;

/**
* MyEclipse Struts
* Creation date: 01-25-2007
*
* XDoclet definition:
* @struts.action validate="true"
*/
public class ShowTopicAction extends Action {
        /*
         * Generated Methods
         */

        /**
         * Method execute
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @return ActionForward
         */
        public ActionForward execute(ActionMapping mapping, ActionForm form,
                        HttpServletRequest request, HttpServletResponse response) {
                // TODO Auto-generated method stub
                int id=Integer.parseInt((String)request.getParameter("id"));
                TopicDAO topDao=new TopicDAO();
                Set set=topDao.getTopic(id);
                request.setAttribute("list", set);
                return mapping.findForward("show");
        }
}

ShowReponseAction:显示REPONSE
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package org.bbs.struts.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hiber.ReponseDAO;
import org.hiber.Topic;
import org.hiber.TopicDAO;

/**
* MyEclipse Struts
* Creation date: 01-25-2007
*
* XDoclet definition:
* @struts.action validate="true"
*/
public class ShowReponseAction extends Action {
        /*
         * Generated Methods
         */

        /**
         * Method execute
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @return ActionForward
         */
        public ActionForward execute(ActionMapping mapping, ActionForm form,
                        HttpServletRequest request, HttpServletResponse response) {
                // TODO Auto-generated method stub
                int id=Integer.parseInt((String)request.getParameter("id"));
                ReponseDAO rDao=new ReponseDAO();
                List topList=new ArrayList();
                TopicDAO tDao=new TopicDAO();
                Topic topic=tDao.findById(id);
                Set set=rDao.getReponseList(id);
                request.setAttribute("topic", topic);
                request.setAttribute("list", set);
                return mapping.findForward("show");
        }
}

show.jsp:

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<html>
        <head>
                <title>JSP for ShowForm form</title>
        </head>
        <body>
                <html:form action="/show">
                        <html:submit/><html:cancel/>
                </html:form>
        </body>
</html>

showForum.jsp:
<%@ page language="java" pageEncoding="gbk"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
  <head>
    <html:base />
   
    <title>showForum.jsp</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">   
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->

  </head>
  
  <body>
    <table border=1>
      
      <tr>
       <td>论坛ID</td><td>论坛名</td>
      </tr>
     
      
        <logic:iterate name="forumList" id="list" scope="request">
        <tr>
         <td>
           <bean:write name="list" property="id"/>
         </td>

         <td>
           <html:link href="./showTopic.do?" paramName="list" paramProperty="id" paramId="id"> <bean:write name="list" property="name"/></html:link>

         </td>
         
         </tr>
        </logic:iterate>
      
    </table>

  </body>
</html:html>

showTopic.jsp:

<%@ page language="java" pageEncoding="gbk"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
  <head>
    <html:base />
   
    <title>showTopic.jsp</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">   
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->

  </head>
  
  <body>
     <table border=1>
      
      <tr>
       <td>主题ID</td><td>主题标题</td><td>主题作者</td>
      </tr>
     
      
        <logic:iterate name="list" id="list" scope="request">
        <tr>
         <td>
           <bean:write name="list" property="id"/>
         </td>
         
         <td>
            <html:link href="./showReponse.do?" paramName="list" paramProperty="id" paramId="id"> <bean:write name="list" property="title"/></html:link>
         </td>
         <td><bean:write name="list" property="author"/></td>
      
         </tr>
        </logic:iterate>
      
    </table>

  </body>
</html:html>

showReponse.jsp:
<%@ page language="java" pageEncoding="gbk"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
  <head>
    <html:base />
   
    <title>showReponse.jsp</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">   
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->

  </head>
  
  <body>
    <table border=1>
      
      <tr>
       <td>主题标题</td><td>主题内容</td><td>主题作者</td>
      </tr>
     
      <tr>
       <td><bean:write name="topic" property="title"></bean:write></td>
       <td><bean:write name="topic" property="cont"></bean:write></td>
       <td><bean:write name="topic" property="author"></bean:write></td>
      </tr>
      <tr>
       <td>回复时间</td><td>回复内容</td><td>回复作者</td>
      </tr>
        <logic:iterate name="list" id="list" scope="request">
        <tr>
         <td>
           <bean:write name="list" property="time"/>
         </td>
         
         <td>
            <bean:write name="list" property="cont"/>
         </td>
         <td><bean:write name="list" property="author"/></td>
      
         </tr>
        </logic:iterate>
      
    </table>

  </body>
</html:html>
发表于 2007-1-25 10:48:24 | 显示全部楼层
发表于 2007-1-25 11:00:40 | 显示全部楼层
发表于 2007-1-25 11:12:45 | 显示全部楼层
您需要登录后才可以回帖 登录 | 建立账号

本版积分规则

 
QQ在线咨询

QQ|小黑屋|手机版|Archiver|美河学习在线 ( 浙网备33020302000026号 )

GMT+8, 2025-5-7 17:03

Powered by Discuz!

© 2001-2025 eimhe.com.

快速回复 返回顶部 返回列表