日期:2014-05-20  浏览次数:20767 次

写了一个删除的数据的小例子(struts2+hibernate)有时会出错,搞不明白,求真相
当我删除的时候有时候会出错,刷新一下以后又有可能会好,搞不明白,求真相!

这是MyEclipse导出的本例子外链下载地址:http://dl.dbank.com/c0jumq5ax6

1、先向数据库插入数据
Java code

public class InsertData {

    public static void main(String[] args){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        for(int i = 0; i<10; i++){
            Person person = new Person();
            person.setName("Test Name " + i);
            person.setAddress("Test address " + i);
            session.save(person);
        }
        session.getTransaction().commit();
    }
}



2、读取数据
Java code

public class ShowData extends ActionSupport{

    private List<Person> persones = new ArrayList<Person>();
    
    public List<Person> getPersones() {
        return persones;
    }

    public void setPersones(List<Person> persones) {
        this.persones = persones;
    }

    public String execute()throws Exception{
        //从数据库读取数据
        String hql = "from Person";
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery(hql);
        this.setPersones((List<Person>)query.list());
        
        session.getTransaction().commit();
        return SUCCESS;
    }
}



3、跳转并显示
HTML code

<body>
  <s:debug/>
  <table>
           <s:iterator value="persones" id="person">
               <tr>
                   <td><s:property value="#person.name"/></td>
                   <td><s:property value="#person.address"/></td>
                   <td><a href="deletePerson?id=<s:property value="#person.id"/>">删除</a></td>
               </tr>
           </s:iterator>
   </table>
  </body>



4、通过ID来删除
Java code

public class DeleteUtil extends ActionSupport{

    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    
    public String execute()throws Exception{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Person person = (Person)session.get(Person.class, this.getId());
        session.delete(person);
        session.getTransaction().commit();
        return SUCCESS;
    }
}



5、调用完以后跳回到showData
XML code

<package name="default" namespace="/" extends="struts-default">
         <action name="showData" class="com.myTest.ShowData">
             <result>/ShowData.jsp</result>
         </action>
         
         <action name="deletePerson" class="com.myTest.DeleteUtil">
             <result type="redirectAction">
                 <param name="actionName">showData</param>
                 <param name="namespace">/</param>
             </result>
         </action>
     </package>



6、这是hibernate文档中的那个帮助类
Java code