hibernate最重要的就是.hbm.xml对应文件,实体之间的一对一、一对多和多对多关系都体现在这个配置文件中。
struts整合hibernate,先要整合struts,就是添加struts的JAR包,然后配置web.xml配置文件,配置struts过滤器,然后在添加hibernate的JAR包,添加hibernate主配置文件hibernate.cfg.xml,然后根据类与表的对应关系配置相应的hbm.xml文件。
hibernate提供了一种HQL查询语言——Hibernate Query Language,HQL面向的是对象而不是数据库中的表,这是与SQL(Structured Query Language)之间的差别
使用struts、hibernate开发一个注册信息的小程序:一个注册页面,提交后显示所有用户信息,单击其中一个用户名,显示单用户详细信息,每行后面有update和delete链接,单击update,显示单用户信息页,同时可以修改密码,年龄,单击delete,删除此条记录,如下:
username | password | age | registerDate | update | delete |
---|---|---|---|---|---|
zdy | qwwqwq | 30 | 13-8-27 | update | delete |
rte | qwer | 12 | 13-8-28 | update | delete |
tty | qw | 21 | 13-8-28 | update | delete |
ertty | w33 | 32 | 13-8-28 | update | delete |
ertty | 222222 | 3211 | 13-8-28 | update | delete |
是对上一个程序的完善:
程序的开发包结构:
注册页面调用action,action调用service,service调用DAO
1、页面部分
注册页面register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'register.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="savePerson.action"> username:<input type="text" name="username" size="20"/><br/> password:<input type="password" name="password" size="20"/><br/> age:<input type="text" name="age" size="20"/><br/> <input type="submit" value="submit"/> </form> </body> </html>
提交后显示listAll.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'listAll.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <table width="80%" align="center" border="1"> <tr> <th>username</th> <th>password</th> <th>age</th> <th>registerDate</th> <th>update</th> <th>delete</th> </tr> <s:iterator value="#request.list" id="person"> <tr> <td> <s:a href="getsinglePerson.action?id=%{#person.id}"><s:property value="username" /></s:a> </td> <td> <s:property value="password" /> </td> <td> <s:property value="age" /> </td> <td> <s:property value="registerDate" /> </td> <td> <s:a href="updatePPerson.action?id=%{#person.id}">update</s:a> </td> <td> <s:a href="deletePerson.action?id=%{#person.id}">delete</s:a> </td> </tr> </s:iterator> </table> </body> </html>
点击用户名显示单户详细信息页面getsinglePerson.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'getsinglePerson.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> username:<s:property value="#request.person.username"/><br/> password:<s:property value="#request.person.password"/><br/> age:<s:property value="#request.person.age"/><br/> registerDate:<s:property value="#request.person.registerDate"/><br/> </body> </html>
点击update进入单户信息修改页面updatePerson.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'updatePerson.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="updatePerson.action"> username:<s:textfield name="username" value="%{#request.person.username}" readonly="true"></s:textfield><br/> password:<s:password name="password" value="%{#request.person.password}"></s:password><br/> age:<s:textfield name="age" value="%{#request.person.age}"></s:textfield><br/> registerDate:<s:textfield name="registerDate" value="%{#request.person.registerDate}" readonly="true"></s:textfield><br/> <s:hidden name="id" value="%{#request.person.id}"></s:hidden> <input type="submit" value="submit"/> </form> </body> </html>
2、struts的action部分,这里只是用了一个action:PersonAction.java
import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.hibernate.Session; import com.cdtax.model.Person; import com.cdtax.service.PersonService; import com.cdtax.service.impl.PersonServiceImpl; import com.cdtax.util.HibernateUtil; import com.opensymphony.xwork2.ActionSupport; public class PersonAction extends ActionSupport { private int id; private String username; private String password; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String savePerson() throws Exception { Person person = new Person(); person.setUsername(username); person.setPassword(password); person.setAge(age); java.sql.Date registerDate = new java.sql.Date(new java.util.Date().getTime()); person.setRegisterDate(registerDate); PersonService personService = new PersonServiceImpl(); personService.savePerson(person); List<Person> list = personService.listAllPersons(); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("list", list); return SUCCESS; } public String deletePerson() throws Exception { PersonService personService = new PersonServiceImpl(); personService.removePerson(id); List<Person> list = personService.listAllPersons(); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("list", list); return SUCCESS; } public String getsinglePerson() throws Exception { PersonService personService = new PersonServiceImpl(); Person person = personService.getsinglePerson(id); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("person", person); return SUCCESS; } public String updatePerson() throws Exception { PersonService personService = new PersonServiceImpl(); Person person = personService.getsinglePerson(id); person.setPassword(password); person.setAge(age); personService.updatePerson(person); List<Person> list = personService.listAllPersons(); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("list", list); return SUCCESS; } }
3、struts的配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="hibernate" extends="struts-default"> <action name="savePerson" class="com.cdtax.action.PersonAction" method="savePerson"> <result name="success">/listAll.jsp</result> </action> <action name="deletePerson" class="com.cdtax.action.PersonAction" method="deletePerson"> <result name="success">/listAll.jsp</result> </action> <action name="getsinglePerson" class="com.cdtax.action.PersonAction" method="getsinglePerson"> <result name="success">/getsinglePerson.jsp</result> </action> <action name="updatePPerson" class="com.cdtax.action.PersonAction" method="getsinglePerson"> <result name="success">/updatePerson.jsp</result> </action> <action name="updatePerson" class="com.cdtax.action.PersonAction" method="updatePerson"> <result name="success">/listAll.jsp</result> </action> </package> </struts>
4、service部分,包括接口和实现
import java.util.List; import com.cdtax.model.Person; public interface PersonService { public void savePerson(Person person); public List<Person> listAllPersons(); public void removePerson(Integer id); public Person getsinglePerson(Integer id); public void updatePerson(Person person); }
import java.util.List; import com.cdtax.dao.PersonDAO; import com.cdtax.dao.impl.PersonDAOImpl; import com.cdtax.model.Person; import com.cdtax.service.PersonService; public class PersonServiceImpl implements PersonService { public void savePerson(Person person) { PersonDAO personDAO = new PersonDAOImpl(); personDAO.savePerson(person); } public List<Person> listAllPersons() { PersonDAO personDAO = new PersonDAOImpl(); return personDAO.listAllPersons(); } public void removePerson(Integer id) { PersonDAO personDAO = new PersonDAOImpl(); personDAO.removePerson(id); } public Person getsinglePerson(Integer id) { PersonDAO personDAO = new PersonDAOImpl(); return personDAO.getsinglePerson(id); } public void updatePerson(Person person) { PersonDAO personDAO = new PersonDAOImpl(); personDAO.updatePerson(person); } }
5、DAO部分,包括接口和实现
import java.util.List; import com.cdtax.model.Person; public interface PersonDAO { public void savePerson(Person person); public List<Person> listAllPersons(); public void removePerson(Integer id); public Person getsinglePerson(Integer id); public void updatePerson(Person person); }
import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.cdtax.dao.PersonDAO; import com.cdtax.model.Person; import com.cdtax.util.HibernateUtil; public class PersonDAOImpl implements PersonDAO { public void savePerson(Person person) { Session session = HibernateUtil.openSession(); Transaction tx = session.beginTransaction(); try { session.save(person); tx.commit(); } catch(Exception ex) { if(null != tx) { tx.rollback(); } ex.printStackTrace(); } finally { HibernateUtil.close(session); } } public List<Person> listAllPersons() { Session session = HibernateUtil.openSession(); Transaction tx = session.beginTransaction(); List<Person> list = null; try { Query query = session.createQuery("from Person"); //Person是类的名字而不是表的名字,需要严格区分大小写 list = (List<Person>)query.list(); tx.commit(); } catch(Exception ex) { if(null != tx) { tx.rollback(); } } finally { HibernateUtil.close(session); } return list; } public void removePerson(Integer id) { Session session = HibernateUtil.openSession(); Transaction tx = session.beginTransaction(); try { Person person = (Person)session.get(Person.class,id); session.delete(person); tx.commit(); } catch(Exception ex) { if(null != tx) { tx.rollback(); } } finally { HibernateUtil.close(session); } } public Person getsinglePerson(Integer id) { Session session = HibernateUtil.openSession(); Transaction tx = session.beginTransaction(); Person person = null; try { person = (Person)session.get(Person.class,id); tx.commit(); } catch(Exception ex) { if(null != tx) { tx.rollback(); } } finally { HibernateUtil.close(session); } return person; } public void updatePerson(Person person) { Session session = HibernateUtil.openSession(); Transaction tx = session.beginTransaction(); try { session.update(person); tx.commit(); } catch(Exception ex) { if(null != tx) { tx.rollback(); } } finally { HibernateUtil.close(session); } } }
6、辅助部分:
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch(Exception ex) { ex.printStackTrace(); } } public static Session openSession() { Session session = sessionFactory.openSession(); return session; } public static void close(Session session) { if(null !=session) { session.close(); } } }
7、关于session的get与load方法都可以获取相应的持久化对象,如果该对象存在,那么这两个方法的行为是一样的;如果该对象不存在,那么get方法返回null而load方法则抛出异常。
关于页面中使用了OGNL表达式,主要应注意#以及%{#}的用法,什么时候用#,什么时候用%{}
hibernate持久化主要体现在session的save(),get(),delete(),update(),createQuery()上。
Transaction tx = session.beginTransaction();主要作用就是执行conn.setAutoCommit(false);对于使用jdbc直接进行数据库操作,默认一个语句执行是自动提交的,如果我们有一组sql语句要作为一个整体执行,就需要取消自动提交,如有:
sql1
sql2
sql3
前面加上Transaction tx = session.beginTransaction();,就相当于:
conn.setAutoCommit(false);
sql1;
sql2;
sql3;
conn.commit();