1. 程式人生 > >實踐hibernate的應用——struts2+hibernate的簡單學生資訊管理

實踐hibernate的應用——struts2+hibernate的簡單學生資訊管理

struts2+hibernate的簡單學生資訊管理,沒有用很好的介面,目的主要是為了實踐一下hibernate框架的學習,深入瞭解hibernate框架。

下面是專案的目錄:



配置檔案hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/stu</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 顯示sql語句 -->
        <property name="hibernate.show_sql">true </property>  
        <property name="format_sql">true</property><!-- 讓輸出的sql語句格式化 -->
        <mapping resource="PO/Stuinfo.hbm.xml"/>
    </session-factory>

</hibernate-configuration>
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="studentAction.LookMessageAction">
            <result name="success">/student/lookMessage.jsp</result>
            <result name="input">/student/index.jsp</result>
        </action>
        <action name="addMessageAction" class="studentAction.AddMessageAction">
            <result name="success" type="chain">lookMessageAction</result>
            <result name="input">/student/addMessage.jsp</result>
        </action>
        <action name="findMessageAction" class="studentAction.FindMessageAction">
            <result name="success">/student/updateMessage.jsp</result>
            <result name="input">/student/findMessage.jsp</result>
        </action>
        <action name="updateMessageAction" class="studentAction.UpdateMessageAction">
            <result name="success" type="chain">lookMessageAction</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</result>
        </action>    
    </package>
</struts>
對映檔案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" length="20" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="name" length="20" not-null="true" />
        </property>
        <property name="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="10" scale="0" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

StudentDao.java檔案

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=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;
        }
    }
    public List<Stuinfo> findInfo(String type,Object value){
        session=HibernateSessionFactory.getSession();
        if(session==null){
       	 System.out.println("dao中session是空的");
        }
        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="提示資訊";
        JOptionPane.showMessageDialog(null, mess, title, type);
    }
}

模組一:查詢所有的的學生資訊

查詢資訊主要是進入lookMessageAction,查詢資料庫:

<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();
        //查詢所有資訊
        List<Stuinfo> list=dao.findAllInfo();
        //把資訊放在session裡面
        request.getSession().setAttribute("count", list.size());
        request.getSession().setAttribute("allInfo", list);
        message="success";
        return message;
    }

StudentDao.java中的部分:
<strong> </strong> public List<Stuinfo> findAllInfo(){
        session=HibernateSessionFactory.getSession();
        try{
            transaction=session.beginTransaction();
            String queryString="from Stuinfo";//HQL語言
            query=session.createQuery(queryString);//建立query物件
            List<Stuinfo> list=query.list();
            transaction.commit();
            session.close();
            return list;
        }catch(Exception e){
            message("findInfo.error:"+e);
            e.printStackTrace();
            return null;
        }
    }

模組二:新增學生資訊

新增學生資訊,點選確定時通過form表單提交addMessageAction,addMessageAction

處理完成之後伺服器跳轉到lookMessageAction。即新增成功之後馬上可檢視所有學生資訊。


 <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 age) {
        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","學號不允許為空!");
        }else{
            StudentDao dao=new StudentDao();
            List<Stuinfo> list=dao.findInfo("id", this.getId());
            if(!list.isEmpty()){
                addFieldError("id","學號已存在!");
            }
        }
        if(this.getName()==null||this.getName().length()==0){
            addFieldError("name","姓名不允許為空!");
        }
        if(this.getAge()>130){
            addFieldError("age","請認真核實年齡!");
        }
        if(this.getWeight()>500){
            addFieldError("weight","請認真核實體重!");
        }
    }
    public String execute() throws Exception{
        StudentDao dao=new StudentDao();
        //把持久化物件儲存在mysql中,此處用到hibernate框架
        boolean save=dao.saveInfo(info());
        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="提示資訊";
        JOptionPane.showMessageDialog(null, mess, title, type);
    }
}
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;
        }
    }

模組三:修改學生資訊
修改學生資訊,首先要選擇序號,點選確定之後,進入修改介面



<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部分
   public String execute() throws Exception{
        request=ServletActionContext.getRequest();
        StudentDao dao=new StudentDao();
        //通過id查詢要修改的學生物件
        List<Stuinfo> list=dao.findInfo("id", this.getId());
        request.getSession().setAttribute("oneInfo", list);
        message="success";
        return message;
    }

在更新頁面填好資訊後,通過form提交到updateMessageAction,updateMessageAction更新成功後伺服器跳轉到lookMessageAction

<action name="updateMessageAction" class="studentAction.UpdateMessageAction">
            <result name="success" type="chain">lookMessageAction</result>
            <result name="input">/student/updateMessage.jsp</result>
        </action>
updateMessageAction.java的部分:
 public String execute() throws Exception{
        StudentDao dao=new StudentDao();
        boolean update=dao.updateInfo(info());//更新資料庫
        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;
    }
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;
        }
    }

模組四:刪除學生資訊
刪除學生資訊也是一樣的,先根據學號查詢到學生資訊,變成持久化物件然後在刪除


<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();
        //從資料庫中刪除
        boolean del=dao.deleteInfo(this.getId());
        if(del){
            message="success";
        }
        return message;
    }
StudentDao.java中的部分
 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;
        }
    }