Adding Hibernate to a Java Application - Hibernate Mappings for Existing Domain Objects
(Page 2 of 4 )
To replace this architecture with one based on Hibernate, we first have to create mapping files that define the relationship between the domain objects and the database. Looking again at Product, we’ll create a mapping file called Product.hbm.xml which looks like:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/ hibernate-mapping-2.0.dtd">
<hibernate-mapping
package="org.springframework.samples. ipetstore.domain">
<class name="Product" table="product">
<id name="productId"
column="productId"
type="string">
<generator class="native"/>
</id>
<property name="categoryId" column="category" type="string"/>
<property name="name" column="name" type="string"/>
<property name="description" column="description" type="string"/>
</class>
</hibernate-mapping>
In the mapping file, we first identify the package and particular class (org. springframework.samples.jpetstore.domain.Product) that we are mapping. We have to tell it what table to map to ("product", in this case) and then map the individual properties of the domain object to the columns in the table. This file needs to be saved somewhere on the class path; we’ll create a new folder in the project structure called “hibernate” to hold our map files and our new DAOs.
Hibernate DAOs
The next step is to create a DAO that uses Hibernate as the persistence layer instead of the SQL mappings used in the original version. The new DAO needs to implement the ProductDao interface, just like the original DAO. However, the implementation of that interface will be totally different.
Here is the code for the new DAO:
public class HibernateProductDao implements ProductDao{
SessionFactory factory;
Configuration cfg;
public HibernateProductDao() {
try {
cfg = new Configuration().addClass(
org.springframework.samples. jpetstore.domain.Product.class);
factory = cfg.buildSessionFactory();
} catch (Exception ex) {
System.out.println("Hibernate configuration failed: " + ex);
}
}
public List getProductListByCategory(String categoryId)
throws DataAccessException {
List results = null;
try {
Session session = factory.openSession();
results = session.find("from product where product.category = ?",
categoryId, Hibernate.STRING);
session.close();
} catch (Exception ex) {
System.out.println("Failed to connect to database:" + ex);
}
return results;
}
public List searchProductList(String keywords) throws DataAccessException {
return null;
}
public Product getProduct(String productId) throws DataAccessException {
Product p = null;
try {
Session session = factory.openSession();
p = (Product)session.load(Product.class, productId);
session.close();
} catch (Exception ex) {
System.out.println("failed to connect to database: " + ex);
p = null;
}
return p;
}
}
First, we need a way to interact with Hibernate. As shown in Chapter 7, we need to create a HibernateSessionFactoryand use it to get aSessionwith which to interact with the database. The DAO’s constructor instantiates a new Hibernate
configuration, loading the mapping file from the class path based on the name of the class added to the configuration. Then, it gets theSessionFactoryfrom the Configuration.
Each method uses the SessionFactory to open a newSessionwith the database. ThegetProductmethod is the most straightforward; first, we get the Session. Then, we ask the session to load an instance of theProductclass, given its productId. Note that the result from thesession.load()call is of typeObject, which we have to cast to Product. Finally, we close the Session. Hibernate handles all the SQL commands, looking up the mapping files, matching the productId to the right column in the table, populating all the fields, everything.
ThegetProductListByCategory()method is less straightforward; it takes acategoryIdand returns a List of all the products that match that category. In this case, we can’t rely on the built-in SQL generation; we have to create our own query. Again, we first grab aSessionfrom theSessionFactory, then use thesession.find()method, which returns aList ofObjects. Find takes three parameters in this case: the HSQL query (which contains a placeholder for a query parameter, marked with a “?”), the value to fill into the query parameter, and the type of that parameter.
As shown in Chapter 7, HSQL (Hibernate SQL) queries look a lot like regular SQL statements, except here we left off the “SELECT [values]” part of the statement, since Hibernate will fill those in for us based on the mapping. This method will now look up all the rows in the Product table wherecategoryIdequals the value passed in to the method, and create one instance ofProductfor each row in the resultset. All the product instances are placed in aListand returned.
The final method of the DAO,searchProductList, would be a lot more complex, but luckily, we don’t have to implement it. Since we have already replaced the original search functionality with the Simple Spider, this method will never be called now, so we simply returnnull(we have to do something, since theProductDaointerface still mandates its inclusion).
To finish out the new architecture, we just repeat these steps for each of the remaining five domain objects. Each gets a mapping file and an implementation of the appropriate DAO interface.
Next: Changing the Application Configuration >>
More Java Articles
More By O'Reilly Media
|
This article is excerpted from the book Better, Faster, Lighter Java, written by Bruce A. Tate and Justin Gehtland (O'Reilly; ISBN: 0596006764). Check it out today at your favorite bookstore. Buy this book now.
|
|