写了一个删除的数据的小例子(struts2+hibernate)有时会出错,搞不明白,求真相
当我删除的时候有时候会出错,刷新一下以后又有可能会好,搞不明白,求真相!
这是MyEclipse导出的本例子外链下载地址:http://dl.dbank.com/c0jumq5ax6
1、先向数据库插入数据
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(); }}
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; }}
<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>
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; }}
<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>
public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; }}
public class Person { private Integer id; private String name; private String address;
Transaction tx=session.beginTransaction();.......tx.commit();