实践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;
        }
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-22 21:12:20

实践hibernate的应用——struts2+hibernate的简单学生信息管理的相关文章

vue实现简单学生信息管理案例

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生信息管理</title> <link rel="stylesheet" href="./lib/bootstrap.css"> <script src="./lib/vue.js&quo

Struts2+Hibernate+Spring框架实现增删改查

一.添加3个框架的JAR包,完成后写配置文件: 1.web配置文件: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation=&quo

struts2+hibernate+spring简单整合且java.sql.SQLException: No suitable driver 问题解决

最近上j2ee的课,老师要求整合struts2+hibernate+spring,我自己其实早早地有准备弄的,现在都第9个项目了,无奈自己的思路和头绪把自己带坑了,当然也是经验问题,其实只是用myeclipse进行整合的,本来也没那么多问题,看视频吧居然好多要手打,我不喜欢看不下去放弃了,教程把就是一堆坑,最最让人不解的是明明有一个冲突是需要解决的,但我看到的教程居然都没有提到,还有一个错误居然好多人都好像自动忽略一样,能解决我问题的都是要漫长的找,所以我一定一定要把这个过程记录下来,给第一次搞

简单Spring+Struts2+Hibernate框架搭建

使用Maven+Spring+Struts2+Hibernate整合 pom文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd

struts2&amp;&amp;Hibernate Demo1

这篇文章和<struts1&&Hibernate Demo1>基本类似,我这里只是拷贝代码了. 最核心的代码:LoginAction.java package action; import org.hibernate.Session; import org.hibernate.Transaction; import hibernate.HibernateSessionFactory; import com.opensymphony.xwork2.ActionSupport; p

Spring+Struts2+Hibernate的整合

这篇主要采用Maven搭建Spring+Struts2+Hibernate的整合项目,复习一下SSH框架,虽然spring提供自己的MVC框架, 但是Spring也提供和其他框架的无缝整合,采用组件形式对个框架进行管理,项目实例是按照真实企业里面的开发搭建,也是web的最后一片了.数据库使 用mysql,连接池使用的是Druid数据源(这些都无关紧要,可以随时的替换),下面就将详细的介绍一下Maven搭建 Spring,Struts2,和hibernation的步奏. 1.数据库设计 数据库库表

SSH开发实践part1:Spring与Hibernate整合

1 之前把SSH看完了,现在从头开始进行项目实践.现在讲整个过程中的点滴记录下来,希望对后来者有参考. 2 SSH是一个轻量级的java开发框架,struts负责MVC开发模式中的controller角色,hibernate则是负责对象的持久化,也就是对DB的访问,spring则是利用其IOC反转控制来完成对bean对象的管理,包括对hibernate的管理.好吧,这些东西相信大家都不陌生.现在我们正式开始,整个开发步骤主要包括以下几点: 新建web project项目 增加spring与hib

Struts2+Hibernate+Spring 整合示例[转]

原文 http://blog.csdn.net/tkd03072010/article/details/7468769 Spring整合Struts2.Hibernate原理概述: 从用户角度来看,用户发出HTTP请求,当MVC框架的控制器组件拦截到用户请求时,将调用系统的业务逻辑组件,业务逻辑组件则调用系统的DAO组件,而DAO组件则依赖于SessionFactory和DataSource等底层组件实现数据库访问. 从系统实现角度看,Ioc容器先创建SessionFactory和DataSou

Spring struts2 hibernate MyBatis SpringMVC 原理

Spring原理 最核心的就是IOC,动态注入DI,利用java里的反射,让一个对象的创建不用new了,可以自动的生产.Spring就是在运行时,跟xml Spring的配置文件来动态的创建对象,和调用对象里的方法的 .其实就是利用java里的反射,反射其实就是在运行时动态的去创建.调用对象. Spring还有一个核心就是AOP这个就是面向切面编程,可以为某一类对象 进行监督和控制(也就是 在调用这类对象的具体方法的前后去调用你指定的 模块)从而达到对一个模块扩充的功能.这些都是通过 配置类达到