Using open source project Hibernate Develop blog system

Source: Internet
Author: User
Tags add date final getdate mysql net string mysql database
The project development tool uses the MYECLIPS3.6, first is establishes the project, the import struts+hibernate package, then configures the SRC and the directory hibernate.cfg.xml. I'm using the MySQL database , So the configuration is as follows:





 
   
   

   
       !--Properties-->
        root< /property>
        jdbc:mysql://localhost:3306/tonnyblog
        net. SF . Hibernate.dialect.MySQLDialect
       
        org.gjt.mm.mysql.driver

       !--mapping files-->
       
   
   

   

Hibernate-configuration>
mapping is the corresponding mapping for JavaBean.





below we continue to hibernate the next step of the program to write





 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 February 6, 2004


*/


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 () {





    }


}
Create 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 ();
    &NBSP

     public void Destroy () {
         try{
& nbsp            hibernateutil.closesession ();
         }
         catch (hibernateexception hex) {
            &NBSP;H Ex.printstacktrace ();
        

     }

}
The above is the basic configuration of the Hibernate, use DAO mode to the database operation, add the following configuration:





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 Add Configuration





  
   processorclass= "Com.tonny.blog.struts.controller.IndexRequestProcessor"/>
   

plug-in classname= "Com.tonny.blog.struts.plugin.HibernatePlugin"


below we define the service layer:





public class servicefactory{
    private static servicefactory Instance

    public synchronized static Servicefactory getinstance () {
        if (instanc E = 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 to 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;


    }





}
Below is how the action invokes the above services:





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);
 }

}
The next step is to manipulate the database for the DAO Layer:





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 Call the strength of the method:





 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 ("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;


    }


}
Here implementation of the database query, modify, delete operations, no many-to-many operation.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.