-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Is this transaction okay?
PostPosted: Thu Jul 31, 2008 10:38 pm 
Newbie

Joined: Wed Aug 01, 2007 4:00 am
Posts: 8
Hello Friends

I am a Hibernate/Spring newbie. The following piece of code

public void saveProduct(final Product product, final Integer manufacturerId)
{
Manufacturer manufacturer = manufacturerDAO.loadManufacturer(manufacturerId);
product.setManufacturedBy(manufacturer);
manufacturer.addProduct(product);
manufacturerDAO.saveManufacturer(manufacturer);
}

gave me the error

failed to lazily initialize a collection of role: no session or session was closed.


Then I tried the following code to programmatically add transaction to update the product table

public void saveProduct(final Product product, final Integer manufacturerId)
{
PlatformTransactionManager pltTrnMgr = PlatformTransactionManager) ApplicationContext.getInstance().getBean("transactionManager");
TransactionTemplate trnTemplate = new TransactionTemplate(pltTrnMgr);
trnTemplate.execute(new TransactionCallbackWithoutResult()
{
@Override
protected void doInTransactionWithoutResult(TransactionStatus trnStatus)
{
try
{
Manufacturer manufacturer = manufacturerDAO.loadManufacturer(manufacturerId);
product.setManufacturedBy(manufacturer);
manufacturer.addProduct(product);
manufacturerDAO.saveManufacturer(manufacturer);
}
catch (Exception ex)
{
trnStatus.setRollbackOnly();
ex.printStackTrace();
}
}
});
}

This is giving the expected result. I just want to know whether this method is okay?. Will this override
the annotation-driven transaction settings given in the DAOs?

These are the related hibernate mapping files and DAOs.


<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="net.sf.hibernate.sample.domain.Manufacturer" table="manufacturer">
<id name="id" type="integer" column="id">
<generator class="native" />
</id>

<property name="manufacturerName" column="manufacturerName" length="255" not-null="true" />

<set name="products" inverse="true" table="product" cascade="all, delete-orphan">
<key column="manufacturerId" not-null="true" />
<one-to-many class="net.sf.hibernate.sample.domain.Product" />
</set>
</class>
</hibernate-mapping>




<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="net.sf.hibernate.sample.domain.Product" table="product">
<id name="id" type="integer" column="id">
<generator class="native" />
</id>

<property name="productName" column="productName" length="255" not-null="true" />
<many-to-one name="manufacturedBy" class="net.sf.hibernate.sample.domain.Manufacturer" column="manufacturerId" not-null="true" />
</class>
</hibernate-mapping>


DOMAINS
=======

public class Product extends BaseObject implements Serializable
{
private static final long serialVersionUID = 1258354709157710736L;
private Integer id;
private String productName;
private Manufacturer manufacturedBy;

............
............

public Manufacturer getManufacturedBy()
{
return manufacturedBy;
}

public void setManufacturedBy(Manufacturer manufacturedBy)
{
this.manufacturedBy = manufacturedBy;
}

}


public class Manufacturer extends LazyPojo
{
private static final long serialVersionUID = 1258354709157710736L;
private Integer id;
private String manufacturerName;
private Set products = new HashSet();

............
............

public Set getProducts()
{
return products;
}

public void setProducts(Set products)
{
this.products = products;
}

public void addProduct(Product aProduct)
{
aProduct.setManufacturedBy(this);
if (products == null)
{
products = new HashSet();
}
products.add(aProduct);
}

public void removeProduct(Product aProduct)
{
products.remove(aProduct);
}
}


DAOs
====
@Transactional(propagation = Propagation.SUPPORTS)
public Manufacturer loadManufacturer(Integer id)
{
StringBuffer hqlQuery = new StringBuffer();
hqlQuery.append("from Manufacturer manufacturer where manufacturer.id = :id");
Query query = _sessionFactory.getCurrentSession().createQuery( hqlQuery.toString());
query.setInteger("id", id);
Manufacturer manufacturer = (Manufacturer) query.uniqueResult();
return manufacturer;
}


@Transactional(propagation = Propagation.REQUIRED)
public void saveProduct(Product product)
{
_sessionFactory.getCurrentSession().saveOrUpdate(product);
}



Thank you.
Sudheer


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 01, 2008 12:09 pm 
Expert
Expert

Joined: Tue May 13, 2008 3:42 pm
Posts: 919
Location: Toronto & Ajax Ontario www.hibernatemadeeasy.com
Looks like you're headed in the right direction.

When you perform database operations, an active Hibernate Session must exist. If it does not, you'll get all sorts of Lazy Loading exceptions. So, your updated code is making sure an active Hibernate Session exists.

Spring and Hibernate are so often used together, that people often think that just knowing Spring will automatically translate into immediate Hibernate skills. Hibernate is definitely easy to use, and it integrates nicely with Spring, but having a good solid understanding of Hibernate will allow you to write even better and more effective code that integrates Spring and Hibernate together.

Here's a quick little tutorial on How Hibernate Works. Give it a read, and it might give you more insight into what Hibernate is doing, and how you might be able to avoid all of these little problems and annoyances you might run into when working with Spring and Hibernate together.

http://www.hiberbook.com/HiberBookWeb/learn.jsp?tutorial=07howhibernateworks

_________________
Cameron McKenzie - Author of "Hibernate Made Easy" and "What is WebSphere?"
http://www.TheBookOnHibernate.com Check out my 'easy to follow' Hibernate & JPA Tutorials


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.