日期:2014-05-20 浏览次数:20755 次
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>