首页 > 开发 > 综合 > 正文

利用开源项目Hibernate开发Blog系统

2024-07-21 02:15:13
字体:
来源:转载
供稿:网友
  开发工具采用myeclips3.6,首先是建立项目,导入struts+hibernate包,然后配置src跟目录下的hibernate.cfg.xml.我采用的是mysql数据库,所以配置如下:

<hibernate-configuration>

    <session-factory>
        <!-- properties -->
        <property name="connection.username">root</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/tonnyblog</property>
        <property name="dialect">net.sf.hibernate.dialect.mysqldialect</property>
        <property name="connection.password"></property>
        <property name="connection.driver_class">org.gjt.mm.mysql.driver</property>

        <!-- mapping files -->
        <mapping resource="com/tonny/blog/bean/user.hbm.xml"/>
   <mapping resource="com/tonny/blog/bean/item.hbm.xml"/>
   <mapping resource="com/tonny/blog/bean/review.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
  mapping为javabean所对应的映射。

  下面我们继续hibernate程序的下步编写

import net.sf.hibernate.hibernateexception;
import net.sf.hibernate.session;
import net.sf.hibernate.sessionfactory;
import net.sf.hibernate.cfg.configuration;

/**
*  description of the class
*
* @author    tonny
* @created    2004年2月6日
*/
public class hibernateutil {

    private final static sessionfactory sessionfactory;

    static {
        try {
            sessionfactory =
                    new configuration().configure().buildsessionfactory();
        } catch (hibernateexception ex) {
            throw new runtimeexception(
                    "exception building sessionfactory: " + ex.getmessage(),ex);
        }
    }

    private hibernateutil(){

    }

    /**
     *  description of the field
     */
    private final static threadlocal session = new threadlocal();


    /**
     *  description of the method
     *
     * @return                         description of the return value
     * @exception  hibernateexception  description of the exception
     */
    public static session currentsession() throws hibernateexception {
        session s = (session) session.get();
        if (s == null) {
            s = sessionfactory.opensession();
            session.set(s);
        }
        return s;
    }


    /**
     *  description of the method
     *
     * @exception  hibernateexception  description of the exception
     */
    public static void closesession() throws hibernateexception {
        session s = (session) session.get();
        session.set(null);
        if (s != null) {
            s.close();
        }
    }

    public static void init(){

    }
}
  创建sessionfactory

import net.sf.hibernate.hibernateexception;
import net.sf.hibernate.sessionfactory;
import net.sf.hibernate.cfg.configuration;

import org.apache.struts.action.actionservlet;
import org.apache.struts.action.plugin;
import org.apache.struts.config.moduleconfig;

import com.tonny.blog.dao.hibernate.hibernateutil;


public class hibernateplugin implements org.apache.struts.action.plugin{
     public void init(actionservlet servlet, moduleconfig config){
       hibernateutil.init();
     }

     public void destroy(){
         try{
             hibernateutil.closesession();
         }
         catch(hibernateexception hex){
             hex.printstacktrace();
         }

     }

}
  以上为hibernate基本配置,对数据库操作采用dao模式,增加配置如下:

import com.tonny.blog.dao.hibernate.*;

public class daofactory {
    private static daofactory instance;

    public synchronized static daofactory getinstance() {
        if (instance == null) {
            instance = new daofactory();
        }
        return instance;
    }
    private daofactory() {
    }

    public itemdao getitemdao(){
        return new itemdaohibernate();
    }

    public reviewdao getreviewdao(){
        return new reviewdaohibernate();
    }

    public userdao getuserdao(){
     return new userdaohibernate();
    }

}
  struts.xml增加配置

<controller contenttype="text/html" debug="3" locale="true" nocache="true"
              processorclass="com.tonny.blog.struts.controller.indexrequestprocessor"/>
  <message-resources parameter="com.tonny.resource"/>
  <plug-in classname="com.tonny.blog.struts.plugin.hibernateplugin"/>
  <plug-in classname="org.apache.struts.tiles.tilesplugin">
    <set-property property="moduleaware" value="true"/>
    <set-property property="definitions-debug" value="0"/>
    <set-property property="definitions-parser-details" value="0"/>
    <set-property property="definitions-parser-validate" value="false"/>
    <set-property property="definitions-config" value="/web-inf/title-def.xml"/>
  </plug-in>
  下面我们定义服务层:

public class servicefactory{
    private static servicefactory instance;

    public synchronized static servicefactory getinstance() {
        if (instance == null) {
            instance = new servicefactory();
        }
        return instance;
    }

    private servicefactory(){

    }
    public  iservice getservice(){
        return new serviceimp();
    }
}
import com.tonny.blog.struts.form.*;
import com.tonny.blog.view.*;
import com.tonny.blog.bean.*;
import java.util.*;
import javax.servlet.http.*;
public interface iservice{
    public usercontainer login(userform userform);
    public boolean logout(usercontainer usercontainer);

    public boolean addblog(blogform blogform,string filepath);
    public boolean removeblog(long id);

    public boolean addreview(long topicid,reviewform reviewform);
    public boolean updateblog(long id,string conten,string topic);
    public boolean removereview(long id);

    public list getitems();
    public itemview getitem(long id);
    public itemview getedititem(long id);
    public list search(searchform searchform);
    /**
     * @param id
     * @param userform
     */
    public boolean adduser(userform userform);

}
import com.tonny.blog.struts.form.*;
import com.tonny.blog.view.*;
import com.tonny.blog.dao.*;
import com.tonny.blog.bean.*;
import java.util.*;
import javax.servlet.http.*;
import com.tonny.blog.struts.util.fileupload;

public class serviceimp implements iservice{
    public usercontainer login(userform userform){
        userdao userdao=daofactory.getinstance().getuserdao();
        user user=userdao.loaduser(userform.getname());
        if(user==null)return new usercontainer("",false);
        if(!user.getpassword().equals(userform.getpassword()))return new usercontainer("",false);
        return new usercontainer(userform.getname(),true);

    }
    public boolean logout(usercontainer usercontainer){

        usercontainer.setlogin(false);
        usercontainer.setname("");
        return true;

    }

    public boolean addblog(blogform blogform,string path) {
        itemdao itemdao=daofactory.getinstance().getitemdao();

        item item=new item(blogform.gettopic(),blogform.getcontent(),
                fileupload.upload(blogform.getfile(),path),new date());
        itemdao.additem(item);
         return true;
    }
    public boolean removeblog(long id) {
        reviewdao reviewdao=daofactory.getinstance().getreviewdao();
        itemdao itemdao=daofactory.getinstance().getitemdao();
         itemdao.removeitem(id);
         return  reviewdao.removereviews(id);
    }

    public boolean addreview(long topicid,reviewform reviewform){
        reviewdao reviewdao=daofactory.getinstance().getreviewdao();
        review review=new review(reviewform.getname(),reviewform.getcontent(),
                                topicid,new date());

        return reviewdao.addreview(review);
    }
    public boolean updateblog(long id,string content,string topic){
        itemdao itemdao=daofactory.getinstance().getitemdao();
        item item=new item();
        item.setid(id);
        item.setcontent(content);
        item.settopic(topic);
        return itemdao.updatitem(item);
    }
    public boolean adduser(userform userform){
        userdao userdao=(userdao) daofactory.getinstance().getuserdao();
        user user=new user(userform.getname(),userform.getpassword());

        return userdao.adduser(user);
    }
    public boolean removereview(long id){
        reviewdao reviewdao=daofactory.getinstance().getreviewdao();
        return reviewdao.removereview(id);
    }

    public list getitems(){
        itemdao itemdao=daofactory.getinstance().getitemdao();
        list items=itemdao.loaditems();
        list itemviews=new arraylist();
        for(iterator it=items.iterator();it.hasnext();){
            item item=(item)it.next();
            itemview itemview=new itemview();
            itemview.setcontent(item.getcontent());
            itemview.setdate(item.getdate());
            itemview.setfile(item.getfile());
            itemview.setid(item.getid());
            itemview.settopic(item.gettopic());
            itemviews.add(itemview);
        }
        return itemviews;
    }

    public itemview getedititem(long id){
        itemdao itemdao=daofactory.getinstance().getitemdao();
        item item=itemdao.loaditem(id);
        itemview itemview=new itemview();
        itemview.setcontent(item.getcontent());
        itemview.setdate(item.getdate());
        itemview.setfile(item.getfile());
        itemview.setid(item.getid());
        itemview.settopic(item.gettopic());
        return  itemview;
    }
    public list search(searchform searchform) {
        itemdao itemdao=daofactory.getinstance().getitemdao();
        list items=itemdao.loaditems(searchform.getkeyword());
        list itemviews=new arraylist();
        for(iterator it=items.iterator();it.hasnext();){
            item item=(item)it.next();
            itemview itemview=new itemview();
            itemview.setcontent(item.getcontent());
            itemview.setdate(item.getdate());
            itemview.setfile(item.getfile());
            itemview.setid(item.getid());
            itemview.settopic(item.gettopic());
            itemviews.add(itemview);
        }
        return itemviews;
    }

}
  下面是action如何调用以上个服务:

import java.io.*;
import javax.servlet.requestdispatcher;
import javax.servlet.servletexception;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpsession;
import javax.servlet.http.httpservletresponse;

import org.apache.struts.action.action;
import org.apache.struts.action.actionerror;
import org.apache.struts.action.actionerrors;
import org.apache.struts.action.actionform;
import org.apache.struts.action.actionforward;
import org.apache.struts.action.actionmapping;
import org.apache.struts.action.actionservlet;
import org.apache.struts.util.messageresources;

import com.tonny.blog.struts.form.*;

public class addblog extends blogbaseaction{


  //------------------------------------------------------------ local forwards
  static final private string forward_success = "success";
  static final private string forward_failure = "failure";

  //------------------------------------------------------------ action methods

  public actionforward execute(actionmapping mapping, actionform form,
      httpservletrequest request, httpservletresponse response)
      throws exception {
     
      if(!islogin(request))return mapping.findforward(forward_failure);
      service.addblog((blogform)form,((blogform)form).getfile().getfilename());
      return mapping.findforward(forward_success);
  }

}
  下一步为dao层来操作数据库:

import com.tonny.blog.bean.*;

import java.util.list;


public interface itemdao {

public boolean additem(item item);

public boolean removeitem(long id);

public list loaditems();

public list loaditems(string topic);

public item loaditem(long id);

public boolean updatitem(item item);


}
  daofactory调用实力化方法:

import com.tonny.blog.dao.*;

import net.sf.hibernate.cfg.configuration;
import net.sf.hibernate.*;
import java.util.*;
import com.tonny.blog.bean.*;


public class itemdaohibernate extends daohibernate implements itemdao {
public itemdaohibernate(){
    }

    public boolean additem(item item){
        try{
         begintransaction();
      session.save(item);
      commit();
            return true;
       }
      catch(hibernateexception e){
            rollback();
            return false;
        }


    }
    public boolean updatitem(item item){
        try{
         begintransaction();
         item it=item;
         it=(item)session.load(item.class,(item.getid()));
         
         it.settopic(item.gettopic());
         system.out.println("item.gettopic()"+item.gettopic());
         it.setcontent(item.getcontent());
         system.out.println("item.getcontent()"+item.getcontent());
          session.flush();
      commit();
            return true;
       }
      catch(hibernateexception e){
          system.err.println("========>hibernate exception"+e);
            rollback();
            return false;
        }


    }
     public boolean removeitem(long id){
        try{
      begintransaction();
       session.delete("from com.tonny.blog.bean.item as item where item.id="+id);
      commit();
            return true;

         }
        catch(hibernateexception e){
            rollback();
            return false;
        }

     }

    public list loaditems(){

     list list=null;
        try{
      begintransaction();
            list=session.find("from com.tonny.blog.bean.item as item");
      commit();
         }
        catch(hibernateexception e){
            system.out.println("load blog failed");
            rollback();

         }
        return list;

    }


    public list loaditems(string topic){
     list list=null;
        try{
         begintransaction();
      query query=session.createquery("from com.tonny.blog.bean.item as item where item.topic like '%"+topic+"%'");
      list=query.list();
         commit();
            return list;

         }
        catch(hibernateexception e){
            system.out.println("load blog failed");
            rollback();
         }
         return list;

    }

    public item loaditem(long id){
        item item=null;
        try{
         begintransaction();
      query query=session.createquery("from com.tonny.blog.bean.item as item where item.id=:id");
    query.setlong("id",id.longvalue());
      iterator it=query.iterate();
      if(it.hasnext()) return item=(item)it.next();
            commit();
         }
        catch(hibernateexception e){
            system.out.println("load blog failed");
            rollback();
         }
         return item;
    }
  }
  这里实现了对数据库查询,修改,删除操作,没有many-to-many操作。
  • 网站运营seo文章大全
  • 提供全面的站长运营经验及seo技术!
  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表