Application of Hibernate in practice--struts2+hibernate simple student Information management

Source: Internet
Author: User

Struts2+hibernate's simple student information management, without a good interface, is intended primarily to practice the learning of hibernate framework and to understand the hibernate framework in depth.

Here is the project's directory:



Configuration file Hibernate.cfg.xml

<?xml version= ' 1.0 ' encoding= ' UTF-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibern                   Ate.sourceforge.net/hibernate-configuration-3.0.dtd "><!--Generated by MyEclipse hibernate Tools. -->Struts.xml

<! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "http://struts.apache.org/dtds/ Struts-2.0.dtd "><struts> <!--Configuration for the default package. --<package name= "Default" extends= "Struts-default" > <action name= "lookmessageaction" class= "St            Udentaction.lookmessageaction "> <result name=" Success ">/student/lookMessage.jsp</result> <result name= "Input" >/student/index.jsp</result> </action> <action name= "AddMessage Action "class=" studentaction.addmessageaction "> <result name=" Success "type=" Chain ">lookmessageaction&        lt;/result> <result name= "input" >/student/addMessage.jsp</result> </action> <action name= "findmessageaction" class= "studentaction.findmessageaction" > <result name= "Success" >/s Tudent/updatemessage.jsp</result> <resuLt name= "input" >/student/findMessage.jsp</result> </action> <action name= "updatemessageact Ion "class=" Studentaction.updatemessageaction "> <result name=" Success "type=" Chain ">lookmessageaction&        lt;/result> <result name= "input" >/student/updateMessage.jsp</result> </action> <action name= "deletemessageaction" class= "studentaction.deletemessageaction" > <result name= "Success "Type=" Chain ">lookMessageAction</result> <result name=" Input ">/student/deletemessage.jsp</re Sult> </action> </package></struts>
mapping Files Stuinfo.hbm.xml

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Generated 2011-12-9 12:17:31 by Hibernate Tools 3.2.1.GA-->< hibernate-mapping> <class name= "PO. Stuinfo "table=" Stuinfo "catalog=" Stu "> <id name=" id "type=" string "> <column name=" id "lengt H= "/> <generator class=" Assigned "/> </id> <property name=" name "type=" Stri ng "> <column name=" name "Length=" not-null= "true"/> </property> <property N        Ame= "Sex" type= "string" > <column name= "Sex" length= "5" not-null= "true"/> </property>         <property name= "age" type= "int" > <column name= "Age" not-null= "true"/> </property> <property name= "Weight" type= "float" > <column name= "Weight" precision="Ten" scale= "0" not-null= "true"/> </property> </class>

Studentdao.java file

Package Dao;import Sessionfactory.hibernatesessionfactory;import PO. Stuinfo;import Java.util.list;import Javax.swing.joptionpane;import Org.hibernate.query;import    Org.hibernate.session;import Org.hibernate.transaction;public class Studentdao {private Transaction Transaction;    Private session session;    private query query; Public Studentdao () {} public boolean saveinfo (Stuinfo info) {try{session=hibernatesessionfactor            Y.getsession ();            Transaction=session.begintransaction ();            Session.save (info);            Transaction.commit ();            Session.close ();        return true;            }catch (Exception e) {message ("Saveinfo.error:" +e);            E.printstacktrace ();        return false; }} public list<stuinfo> Findinfo (String type,object value) {session=hibernatesessionfactory.getsession        ();        if (session==null) {System.out.println ("The session in DAO is empty");          } try{  Transaction=session.begintransaction (); String querystring= "from Stuinfo as model where model."            +type+ "=" +value;            System.out.println (queryString);          Query=session.createquery (queryString);            Query.setparameter (0, value);            List<stuinfo> list=query.list ();            Transaction.commit ();            Session.close ();        return list;            }catch (Exception e) {message ("Findinfo.error:" +e);            E.printstacktrace ();        return null;        }} public list<stuinfo> Findallinfo () {session=hibernatesessionfactory.getsession ();            try{transaction=session.begintransaction ();            String querystring= "from Stuinfo";            Query=session.createquery (queryString);            List<stuinfo> list=query.list ();            Transaction.commit ();            Session.close ();        return list; }catch (Exception e) {message ("Findinfo.error:" +e);            E.printstacktrace ();        return null;            }} public Boolean deleteinfo (String id) {try{session=hibernatesessionfactory.getsession ();            Transaction=session.begintransaction ();            Stuinfo info=new stuinfo ();            info= (Stuinfo) session.get (Stuinfo.class, id);            Session.delete (info);            Transaction.commit ();            Session.close ();        return true;            }catch (Exception e) {message ("Deleteinfo.error:" +e);            E.printstacktrace ();        return false;            }} public Boolean updateInfo (Stuinfo info) {try{session=hibernatesessionfactory.getsession ();            Transaction=session.begintransaction ();            Session.update (info);            Transaction.commit ();            Session.close ();        return true;            }catch (Exception e) {message ("Updateinfo.error:" +e);            E.printstacktrace ();  return false;      }} public void message (String mess) {int type=joptionpane.yes_no_option;        String title= "hint message";    Joptionpane.showmessagedialog (null, mess, title, type); }}

Module One: Query all of the student information

Query information is mainly to enter the Lookmessageaction, query database:

<span style= "FONT-SIZE:24PX;" > <action name= "lookmessageaction" class= "studentaction.lookmessageaction" >            <result name= "Success" >/student/lookMessage.jsp</result>            <result name= "Input" >/student/index.jsp</result>        </action></span>

Lookmessageaction.java

  Public String Execute () throws exception{        request=servletactioncontext.getrequest ();        Studentdao dao=new Studentdao ();        Query All information        list<stuinfo> list=dao.findallinfo ();        Put the information in the session        Request.getsession (). SetAttribute ("Count", List.size ());        Request.getsession (). SetAttribute ("Allinfo", list);        Message= "Success";        return message;    }

Part of the Studentdao.java:

<strong> </strong> public list<stuinfo> findallinfo () {        session= Hibernatesessionfactory.getsession ();        try{            transaction=session.begintransaction ();            String querystring= "from Stuinfo";//hql language            query=session.createquery (queryString);//Create Query Object            list< Stuinfo> list=query.list ();            Transaction.commit ();            Session.close ();            return list;        } catch (Exception e) {            message ("Findinfo.error:" +e);            E.printstacktrace ();            return null;        }    }

Module Two: Add student information

Add student information and submit addmessageaction,addmessageaction via form form when you click OK

The server jumps to lookmessageaction after processing is complete. That is, you can see all student information immediately after you add it.


<action name= "addmessageaction" class= "studentaction.addmessageaction" >            <result name= "Success" Type= " Chain ">lookMessageAction</result>            <result name=" Input ">/student/addmessage.jsp</result >        </action>
Addmessageaction.java

Package Studentaction;import Dao.studentdao;import PO. Stuinfo;import Com.opensymphony.xwork2.actionsupport;import Java.util.list;import Javax.swing.JOptionPane;public    Class Addmessageaction extends actionsupport{private String ID;    private String name;    Private String sex;    private int age;    private float weight;    Private String message= "input";    Public String GetId () {return id;    } public void SetId (String id) {this.id = ID;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public String Getsex () {return sex;    public void Setsex (String sex) {this.sex = sex;    } public int Getage () {return age;    public void Setage (int.) {this.age = age;    } public float Getweight () {return weight;    } public void Setweight (float weight) {this.weight = weight; } public void Validate () {if (This.getid () ==null| | This.getid (). Length () ==0) {addfielderror ("id", "study number not allowed to be empty!");}            else{Studentdao dao=new Studentdao ();            List<stuinfo> list=dao.findinfo ("id", This.getid ());        if (!list.isempty ()) {Addfielderror ("id", "study number already exists!");}} if (This.getname () ==null| |        This.getname (). Length () ==0) {addfielderror ("name", "name not allowed to be empty!");} if (This.getage () >130) {Addfielderror ("age", "please carefully verify the ages!")        "); } if (This.getweight () >500) {addfielderror ("weight", "Please check your weight carefully!")        ");        }} public String execute () throws exception{Studentdao dao=new Studentdao ();        Save the persistence object in MySQL and use the Hibernate framework Boolean Save=dao.saveinfo (info ()) here;        if (save) {message= "success";    } return message;        Public Stuinfo info () {stuinfo info=new stuinfo ();        Info.setid (This.getid ());        Info.setname (This.getname ()); Info.sEtsex (This.getsex ());        Info.setage (This.getage ());        Info.setweight (This.getweight ());    return info;        } public void message (String mess) {int type=joptionpane.yes_no_option;        String title= "hint message";    Joptionpane.showmessagedialog (null, mess, title, type); }}
part of the Studentdao.java:

  public boolean  saveinfo (stuinfo info) {        try{            session=hibernatesessionfactory.getsession ();            Transaction=session.begintransaction ();            Session.save (info);            Transaction.commit ();            Session.close ();            return true;        } catch (Exception e) {            message ("Saveinfo.error:" +e);            E.printstacktrace ();            return false;        }    }

Module Three: Modify student information
To modify student information, first select the serial number, click OK, then go to the edit screen



<span style= "FONT-SIZE:24PX;" ><action name= "findmessageaction" class= "studentaction.findmessageaction" >            <result name= "Success" >/student/updateMessage.jsp</result>            <result name= "Input" >/student/findmessage.jsp</ Result>        </action></span>
Findmessageaction.java Part

   Public String Execute () throws exception{        request=servletactioncontext.getrequest ();        Studentdao dao=new Studentdao ();        Find the Student object to be modified by ID        list<stuinfo> list=dao.findinfo ("id", This.getid ());        Request.getsession (). SetAttribute ("Oneinfo", list);        Message= "Success";        return message;    }

After the update page fills in the information, the server jumps to the lookmessageaction after the form submits to the Updatemessageaction,updatemessageaction update successfully.

<action name= "updatemessageaction" class= "studentaction.updatemessageaction" >            <result name= "Success" Type= "Chain" >lookMessageAction</result>            <result name= "Input" >/student/updatemessage.jsp</ Result>        </action>
part of the Updatemessageaction.java:

Public String Execute () throws exception{        Studentdao dao=new Studentdao ();        Boolean Update=dao.updateinfo (info ());//Update Database        if (update) {            message= "success";        }        return message;    }    Public Stuinfo info () {        stuinfo info=new stuinfo ();        Info.setid (This.getid ());        Info.setname (This.getname ());        Info.setsex (This.getsex ());        Info.setage (This.getage ());        Info.setweight (This.getweight ());        return info;    }
part of the Studentdao.java:

  public boolean updateInfo (Stuinfo info) {        try{            session=hibernatesessionfactory.getsession ();            Transaction=session.begintransaction ();            Session.update (info);            Transaction.commit ();            Session.close ();            return true;        } catch (Exception e) {            message ("Updateinfo.error:" +e);            E.printstacktrace ();            return false;        }    }

Module Four: Delete student information
Delete Student information is also the same, first according to the student number to query information, become persistent object and then delete


<span style= "FONT-SIZE:24PX;" >  <action name= "deletemessageaction" class= "studentaction.deletemessageaction" >            <result name= "Success" type= "Chain" >lookMessageAction</result>            <result name= "Input" >/student/ deletemessage.jsp</result>        </action>   </span>
deletemessageaction. Java

Public String Execute () throws exception{        Studentdao dao=new Studentdao ();        Remove the        boolean del=dao.deleteinfo (This.getid ()) from the database;        if (del) {            message= "success";        }        return message;    }
Part of the Studentdao.java

public Boolean deleteinfo (String id) {        try{            session=hibernatesessionfactory.getsession ();            Transaction=session.begintransaction ();            Stuinfo info=new stuinfo ();            First get the Persistence object            info= (stuinfo) session.get (Stuinfo.class, id);            Re-persisted object            Session.delete (info);            Transaction.commit ();            Session.close ();            return true;        } catch (Exception e) {            message ("Deleteinfo.error:" +e);            E.printstacktrace ();            return false;        }    }






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Application of Hibernate in practice--struts2+hibernate simple student Information management

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.