📄 lib0084.html
字号:
<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>A Hibernate Example</title>
<link rel="STYLESHEET" type="text/css" href="images/xpolecat.css">
<link rel="STYLESHEET" type="text/css" href="images/ie.content.css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;"><a href="toc.html"><img src="images/teamlib.gif" width="62" height="15" border="0" align="absmiddle" alt="Team LiB"></a></div></td>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href="LiB0083.html"><img src="images/previous.gif" width="62" height="15" border="0" align="absmiddle" alt="Previous Section"></a>
<a href="LiB0085.html"><img src="images/next.gif" width="41" height="15" border="0" align="absmiddle" alt="Next Section"></a>
</div></td></tr></table>
<br>
<div class="chapter">
<a name="ch12"></a>
<div class="section">
<h2 class="first-section-title"><a name="387"></a><a name="ch12lev1sec3"></a>A Hibernate Example</h2><p class="first-para">Object-relational toolsets appear to be gaining popularity. To illustrate how you can incorporate an object-relational toolset into a layered architecture, this chapter focuses on the Hibernate toolset, which is hosted at <a target="_top" class="url" href="http://www.hibernate.org/">http://www.hibernate.org/</a>.</p>
<p class="para">Hibernate complements a layered architecture exceptionally well. The toolset requires mapping value objects to tables and columns in the database. With the mapping, Hibernate can read or write to the database using value objects directly. This greatly reduces the amount of Java code needed in DAOs.</p>
<p class="para">Hibernate does have a configuration requirement. It's possible to specify this configuration in an XML file or by coding it in a central utility class. I elected to code Hibernate's configuration in a utility class called <span class="fixed">HibernateEnvironment</span>, the source for which is shown in <a class="internaljump" href="#ch12list03">listing 12.3</a>.</p>
<div class="example">
<span class="example-title"><span class="example-titlelabel">Listing 12.3: </span>Sample Hibernate Configuration</span><a name="388"></a><a name="ch12list03"></a>
<div class="formalbody">
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="Start example" border="0"></b></font></td>
</tr>
</table>
<pre class="literallayout">
1:package book.sample.dao.db;
2:
3:import book.sample.vo.*;
4:import book.sample.env.SampleException;
5:
6:import net.sf.hibernate.SessionFactory;
7:import net.sf.hibernate.HibernateException;
8:import net.sf.hibernate.cfg.Configuration;
9:
10:import java.util.Properties;
11:
12:public class HibernateEnvironment
13:{
14: private static SessionFactory _sessionFactory;
15: static<a name="389"></a><a name="IDX-160"></a>
16: {
17: Properties props = new Properties();
18: props.put( "hibernate.dialect",
19: "net.sf.hibernate.dialect.Oracle9Dialect");
20: props.put(
21: "hibernate.cglib.use_reflection_optimizer",
22: "true");
23: props.put("hibernate.connection.driver_class",
24: "oracle.jdbc.driver.OracleDriver");
25: props.put("hibernate.connection.url",
26: "jdbc:oracle:thin:@localhost:1521:ORA92");
27: props.put( "hibernate.connection.username",
28: "scott");
29: props.put( "hibernate.connection.password",
30: "tiger");
31: props.put( "hibernate.connection.pool_size",
32: "3");
33: props.put( "hibernate.statement_cache.size",
34: "3");
35:
36: Configuration cfg = new Configuration();
37: try
38: {
39: cfg.addClass(OrderedItemVO.class);
40: cfg.addClass(PurchaseOrderVO.class);
41: cfg.setProperties(props);
42:
43: _sessionFactory =
44: cfg.buildSessionFactory();
45: }
46: catch (HibernateException h)
47: {
48: throw new SampleException(
49: "Hibernate configuration error", h);
50: }
51: }
52:
53: public static SessionFactory getSessionFactory()
54: {
55: return _sessionFactory;
56: }
57:}
</pre>
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="End example" border="0"></b></font></td>
</tr>
</table>
<table class="BlankSpace" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td height="16"></td>
</tr>
</table>
</div>
</div>
<p class="para">
<i class="emphasis">Source:</i> /src/book/sample/dao/db/HibernateEnvironment.java</p>
<p class="para">Configuration code such as that in <a class="internaljump" href="#ch12list03">listing 12.3</a> is only executed once when the application is started. It mainly consists of specifying the JDBC driver and connection information as well as registering each value object that can be persisted.</p>
<a name="390"></a><a name="IDX-161"></a>
<p class="para">For each value object registered, a mapping must be created to tell Hibernate which fields in the class correspond to which columns in the database. <a class="internaljump" href="#ch12list04">Listing 12.4</a> is an example mapping for <span class="fixed">PurchaseOrderVO</span>. Most of the content for this mapping can be easily generated by an open source Eclipse plug-in called Hibernator, which is available at <a target="_top" class="url" href="http://sourceforge.net/projects/hibernator/">http://sourceforge.net/projects/hibernator/</a>.</p>
<div class="example">
<span class="example-title"><span class="example-titlelabel">Listing 12.4: </span>Sample Hibernate Value Object Mapping</span><a name="391"></a><a name="ch12list04"></a>
<div class="formalbody">
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="Start example" border="0"></b></font></td>
</tr>
</table>
<pre class="literallayout">
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name=" book.sample.vo.PurchaseOrderVO"
table=" purchase_order">
<id name=" orderNbr" column=" ORDER_NBR"
unsaved-value="0" >
<generator class=" hilo">
<param name=" table">purchase_order_nbr</param>
<param name=" column">next_value</param>
<param name=" max_lo">100</param>
</generator>
</id>
<property name=" customerId" column=" CUSTOMER_ID" />
<property name=" orderDate" column=" DATE_CREATED" />
<property name=" shipDate" column=" DATE_SHIPPED" />
</class>
</hibernate-mapping>
</pre>
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="End example" border="0"></b></font></td>
</tr>
</table>
<table class="BlankSpace" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td height="16"></td>
</tr>
</table>
</div>
</div>
<p class="para">
<i class="emphasis">Source:</i> /src/book/sample/vo/PurchaseOrderVO.hbm.xml</p>
<p class="para">Hibernate has three classes to implement transaction management: <span class="fixed">SessionFactory</span>, <span class="fixed">Session</span>, and <span class="fixed">Transaction</span>. <span class="fixed">Session</span> manages JDBC connections for Hibernate, and as you might expect, <span class="fixed">SessionFactory</span> is needed to establish a <span class="fixed">Session</span>. <span class="fixed">Session</span> objects produce <span class="fixed">Transaction</span> objects that can be used for commits and rollbacks.</p>
<p class="para">As when you use native JDBC, you handle all connection and transaction management logic in the business logic layer. Code illustrating how to use Hibernate <span class="fixed">Session</span> and <span class="fixed">Transaction</span> objects to establish a connection and commit a transaction is presented in <a class="internaljump" href="#ch12list05">listing 12.5</a>.</p>
<div class="example">
<span class="example-title"><span class="example-titlelabel">Listing 12.5: </span>Sample Hibernate Session and Transaction Management</span><a name="392"></a><a name="ch12list05"></a>
<div class="formalbody">
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="Start example" border="0"></b></font></td>
</tr>
</table>
<pre class="literallayout">
1:import book.sample.dao.db.PurchaseOrderDAO;
2:import book.sample.dao.db.HibernateEnvironment;
3:
4:import net.sf.hibernate.Transaction;
5:import net.sf.hibernate.SessionFactory;
6:import net.sf.hibernate.Session;
7:
8:// Some code omitted
9:
10: SessionFactory factory =
11: HibernateEnvironment.getSessionFactory();
12: Session session =
13: factory.openSession();
14: Transaction tx = session.beginTransaction();
15:
16: PurchaseOrderDAO dao =
17: new PurchaseOrderDAO(session);
18: dao.savePurchaseOrder(order);
19:
20: tx.commit();
</pre>
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="End example" border="0"></b></font></td>
</tr>
</table>
<table class="BlankSpace" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td height="16"></td>
</tr>
</table>
</div>
</div>
<a name="393"></a><a name="IDX-162"></a>
<p class="para">Inside the DAO, the Hibernate session object is used to initiate selects, updates, and inserts. <a class="internaljump" href="#ch12list06">Listing 12.6</a> is an example of how to insert.</p>
<div class="example">
<span class="example-title"><span class="example-titlelabel">Listing 12.6: </span>Sample Hibernate Insert</span><a name="394"></a><a name="ch12list06"></a>
<div class="formalbody">
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="Start example" border="0"></b></font></td>
</tr>
</table>
<pre class="literallayout">
1: public void savePurchaseOrder(PurchaseOrderVO order)
2: throws SQLException
3: {
4: try
5: {
6: Integer generatedOrderNbr =
7: (Integer) this._hibernateSession.save(order);
8:
9: OrderedItemVO[] line = order.getOrderedItems();
10: for (int i = 0 ; i < line.length; i++)
11: {
12: line[i].setOrderNbr(
13: generatedOrderNbr.intValue());
14: line[i].setLineNbr(i);
15: this._hibernateSession.save(line[i]);
16: }
17: }
18: catch (Throwable t)
19: {
20: throw new SampleException(<a name="395"></a><a name="IDX-163"></a>
21: "Error saving purchase order: "+
22: order.describe(), t);
23: }
24: }
</pre>
<table class="BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="000080" class="bluecell"><font size="2" face="Arial" color="010100"><b><img src="_.gif" width="1" height="2" alt="End example" border="0"></b></font></td>
</tr>
</table>
<table class="BlankSpace" border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td height="16"></td>
</tr>
</table>
</div>
</div>
<p class="last-para">
<i class="emphasis">Source:</i> /src/book/sample/dao/db/PurchaseOrderDAO.java)</p>
</div>
</div><br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;"><a href="toc.html"><img src="images/teamlib.gif" width="62" height="15" border="0" align="absmiddle" alt="Team LiB"></a></div></td>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href="LiB0083.html"><img src="images/previous.gif" width="62" height="15" border="0" align="absmiddle" alt="Previous Section"></a>
<a href="LiB0085.html"><img src="images/next.gif" width="41" height="15" border="0" align="absmiddle" alt="Next Section"></a>
</div></td></tr></table>
</body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -