-->
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.  [ 5 posts ] 
Author Message
 Post subject: LazyInitializationException
PostPosted: Sat Jan 28, 2006 7:15 pm 
Newbie

Joined: Sat Jan 28, 2006 1:10 pm
Posts: 6
Hi All,
I am getting the LazyInitializationException inspite of setting the lazy="false" and outer-join="true" attributes.
I have the following object model, a User has a one-to-many on ProjectRoles, which is a composite object of Project & Role.

----------------User.hbm.xml---------------
<hibernate-mapping
>
<class
name="com.testing.model.User"
table="app_user"
>

<id
name="id"
column="uid"
type="java.lang.Integer"
unsaved-value="null">

<generator class="native">
</generator>

</id>


<set
name="projectRoles"
table="user_project_role"
lazy="false"
cascade="save-update"
sort="unsorted"
outer-join="true">

<key column="user_id">
</key>

<one-to-many
class="com.testing.model.ProjectRole" />

</set>

</class>

</hibernate-mapping>
-------------------------------------------------------------------
-------------ProjectRole.hbm.xml------------------------------

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class
name="com.testing.model.ProjectRole"
table="user_project_role">

<id
name="id"
column="id"
type="java.lang.Integer"
unsaved-value="null"
>
<generator class="increment">
</generator>
</id>

<many-to-one
name="project"
class="com.testing.model.Project"
cascade="none"
outer-join="true"
update="true"
insert="true"
column="project_id"
not-null="true"
/>

<many-to-one
name="role"
class="com.testing.model.Role"
cascade="none"
outer-join="true"
update="true"
insert="true"
column="role_id"
not-null="true"
/>

</class>

</hibernate-mapping>
---------------------------------------------------------

As you can see, I have the lazy="false" on the projectRoles set in "User".

My java test class below...
--------------------------------------------------------
public class UserDAOTest extends BaseDAOTestCase {
private UserDAO dao = null;
private User user = null;
private ProjectDAO pdao = null;
private Project project = null;
private RoleDAO rdao = null;
private Role role = null;

public void setUserDAO(UserDAO dao) {
this.dao = dao;
}

public void setRoleDAO(RoleDAO rdao) {
this.rdao = rdao;
}

public void setProjectDAO(ProjectDAO pdao)
{
this.pdao = pdao;
}

public void testGetUserInvalid() throws Exception {
try {
user = dao.getUser(new Integer(321));
fail("'badusername' found in database, failing test...");
} catch (DataAccessException d) {
assertTrue(d != null);
}
}

public void testGetUser() throws Exception
{
user = dao.getUser(new Integer(101));
assertNotNull(user);
assertEquals(1, user.getProjectRoles().size());
}

public void testAddUserRole() throws Exception
{
user = dao.getUser(new Integer(101));

assertEquals(1, user.getProjectRoles().size());

ProjectRole prole = ((ProjectRole)(user.getProjectRoles().toArray()[0]));
role = rdao.findRole(Constants.ADMIN_ROLE);
project = pdao.findProject("testing");
ProjectRole projRole = new ProjectRole();
projRole.setProject(project);
projRole.setRole(role);

// This call causes exception
user.addProjectRole(projRole);

dao.saveUser(user);

assertEquals(2, user.getProjectRoles().size());

//add the same role twice - should result in no additional role
user.removeProjectRole(projRole);
dao.saveUser(user);

assertEquals("more than 2 roles", 2, user.getProjectRoles().size());

user.getProjectRoles().remove(projRole);
dao.saveUser(user);

assertEquals(1, user.getProjectRoles().size());
}

}
--------------------------------------------------------------------

results in the following exception

[junit] Testcase: testAddUserRole(com.testing.dao.UserDAOTest): Caused an ERROR
[junit] could not initialize proxy - the owning Session was closed
[junit] org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
[junit] at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:53)
[junit] at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:84)
[junit] at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:134)
[junit] at com.testing.model.Status$$EnhancerByCGLIB$$1019d98.hashCode(<generated>)
[junit] at org.apache.commons.lang.builder.HashCodeBuilder.append(HashCodeBuilder.java:392)
[junit] at com.testing.model.Project.hashCode(Project.java:177)
[junit] at org.apache.commons.lang.builder.HashCodeBuilder.append(HashCodeBuilder.java:392)
[junit] at com.testing.model.ProjectRole.hashCode(ProjectRole.java:74)
[junit] at java.util.HashMap.hash(HashMap.java:261)
[junit] at java.util.HashMap.put(HashMap.java:379)
[junit] at java.util.HashSet.add(HashSet.java:192)
[junit] at org.hibernate.collection.PersistentSet.add(PersistentSet.java:159)
[junit] at com.testing.model.User.addProjectRole(User.java:372)
[junit] at com.testing.dao.UserDAOTest.testAddUserRole(UserDAOTest.java:90)
[junit] TEST com.testing.dao.UserDAOTest FAILED
[junit] Tests FAILED

The exception is being thrown on the

user.addProjectRole(projRole);

call. In the user object, it's a simple getProjectRoles().add(projRole).

Any ideas on where I am going wrong?

Thanks for your time.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jan 29, 2006 1:25 am 
Senior
Senior

Joined: Tue Aug 23, 2005 8:52 am
Posts: 181
How are your DAOs designed? Do they close the session after the operation is over? As per the exception thrown, it looks like the Session is getting closed after the dao.getUser() call.


Top
 Profile  
 
 Post subject: using HibernateDAOSupport
PostPosted: Sun Jan 29, 2006 1:50 am 
Newbie

Joined: Sat Jan 28, 2006 1:10 pm
Posts: 6
I am using Spring's HibernateDAOSupport, which I think closes the session after every call.

----------------BaseDAOHibernate.java-------------
public class BaseDAOHibernate extends HibernateDaoSupport implements DAO {
protected final Log log = LogFactory.getLog(getClass());

/**
* @see com.testing.dao.DAO#saveObject(java.lang.Object)
*/
public void saveObject(Object o) {
getHibernateTemplate().saveOrUpdate(o);
}

/**
* @see com.testing.dao.DAO#getObject(java.lang.Class, java.io.Serializable)
*/
public Object getObject(Class clazz, Serializable id) {
Object o = getHibernateTemplate().get(clazz, id);

if (o == null) {
throw new ObjectRetrievalFailureException(clazz, id);
}

return o;
}

/**
* @see com.testing.dao.DAO#getObjects(java.lang.Class)
*/
public List getObjects(Class clazz) {
return getHibernateTemplate().loadAll(clazz);
}

/**
* @see com.testing.dao.DAO#removeObject(java.lang.Class, java.io.Serializable)
*/
public void removeObject(Class clazz, Serializable id) {
getHibernateTemplate().delete(getObject(clazz, id));
}

}
--------------------------------------------------------------------------
------------------UserDAOHibernate.java------------------------------
public class UserDAOHibernate extends BaseDAOHibernate implements UserDAO {
/**
* @see com.testing.dao.UserDAO#getUser(java.lang.String)
*/
public User getUser(Integer userId) {
User user = (User) getHibernateTemplate().get(User.class, userId);

if (user == null) {
log.warn("uh oh, user '" + userId + "' not found...");
throw new ObjectRetrievalFailureException(User.class, userId);
}

return user;
}

/**
* @see com.testing.dao.UserDAO#getUser(java.lang.String)
*/
public User getUser(String username) {
List list = getHibernateTemplate().find("from User u where u.username=?", new Object[]{username});
Iterator iter = list.iterator();
if (iter.hasNext())
return (User)iter.next();
else
return null;
}

/**
* @see com.testing.dao.UserDAO#getUsers(com.testing.model.User)
*/
public List getUsers(User user) {
return getHibernateTemplate().find("from User");
}

/**
* @see com.testing.dao.UserDAO#saveUser(com.testing.model.User)
*/
public void saveUser(final User user) {
if (log.isDebugEnabled()) {
log.debug("user's id: " + user.getUsername());
}

getHibernateTemplate().saveOrUpdate(user);
// necessary to throw a DataIntegrityViolation and catch it in UserManager
getHibernateTemplate().flush();
}

/**
* @see com.testing.dao.UserDAO#removeUser(java.lang.Integer)
*/
public void removeUser(Integer userId)
{
User user = getUser(userId);
removeUserCookies(user.getUsername());
getHibernateTemplate().delete(user);
}

/**
* @see com.testing.dao.UserDAO#removeUser(java.lang.String)
*/
public void removeUser(String userName)
{
User user = getUser(userName);
removeUserCookies(userName);
getHibernateTemplate().delete(user);
}

}
-------------------------------------------------------------------
---------------------User.java------------------------------------
package com.testing.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
* User class
* @hibernate.class table="app_user"
*/
public class User extends BaseObject implements Serializable {
private static final long serialVersionUID = 3832626162173359411L;

private Integer id;
protected String username;
protected String password;
protected String confirmPassword;
protected String firstName;
protected String lastName;
protected Address address = new Address();
protected String phoneNumber;
protected String email;
protected String website;
protected String passwordHint;
protected Integer version;
protected Boolean superAdmin;
protected Boolean enabled;
protected Set projectRoles = new HashSet();

public User() {
}

public User(String username) {
this.username = username;
}

/**
* @hibernate.id column="uid" generator-class="native" unsaved-value="null"
*
* @return auto generated id of the user
*/
public Integer getId()
{
return id;
}

public void setId(Integer id)
{
this.id = id;
}

/**
* Returns the username.
*
* @return String
*
* @struts.validator type="required"
* @hibernate.property column="username" length="20" not-null="true" unique="true"
*/
public String getUsername() {
return username;
}

/**
* Returns the password.
* @return String
*
* @struts.validator type="required"
* @struts.validator type="twofields" msgkey="errors.twofields"
* @struts.validator-args arg1resource="userForm.password"
* @struts.validator-args arg1resource="userForm.confirmPassword"
* @struts.validator-var name="secondProperty" value="confirmPassword"
* @hibernate.property column="password" not-null="true"
*/
public String getPassword() {
return password;
}

/**
* Returns the confirmedPassword.
* @return String
*
* @struts.validator type="required"
*/
public String getConfirmPassword() {
return confirmPassword;
}

/**
* Returns the firstName.
* @return String
*
* @struts.validator type="required"
* @hibernate.property column="first_name" not-null="true" length="50"
*/
public String getFirstName() {
return firstName;
}

/**
* Returns the lastName.
* @return String
*
* @struts.validator type="required"
* @hibernate.property column="last_name" not-null="true" length="50"
*/
public String getLastName() {
return lastName;
}

public String getFullName() {
return firstName + ' ' + lastName;
}

/**
* Returns the address.
*
* @return Address
*
* @hibernate.component
*/
public Address getAddress() {
return address;
}

/**
* Returns the email. This is an optional field for specifying a
* different e-mail than the username.
*
* @return String
*
* @struts.validator type="required"
* @struts.validator type="email"
* @hibernate.property name="email" not-null="true" unique="true"
*/
public String getEmail() {
return email;
}

/**
* Returns the phoneNumber.
*
* @return String
*
* @struts.validator type="mask" msgkey="errors.phone"
* @struts.validator-var name="mask" value="${phone}"
* @hibernate.property column="phone_number" not-null="false"
*/
public String getPhoneNumber() {
return phoneNumber;
}

/**
* Returns the website.
*
* @return String
*
* @struts.validator type="required"
* @hibernate.property column="website" not-null="false"
*/
public String getWebsite() {
return website;
}

/**
* Returns the passwordHint.
*
* @return String
*
* @struts.validator type="required"
* @hibernate.property column="password_hint" not-null="false"
*/
public String getPasswordHint() {
return passwordHint;
}

/**
* Sets the username.
* @param username The username to set
*/
public void setUsername(String username) {
this.username = username;
}

/**
* Sets the password.
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}

/**
* Sets the confirmedPassword.
* @param confirmPassword The confirmed password to set
*/
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}

/**
* Sets the firstName.
*
* @param firstName The firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}

/**
* Sets the lastName.
* @param lastName The lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}

/**
* Sets the address.
* @param address The address to set
*/
public void setAddress(Address address) {
this.address = address;
}

/**
* Sets the email.
* @param email The email to set
*/
public void setEmail(String email) {
this.email = email;
}

/**
* Sets the phoneNumber.
* @param phoneNumber The phoneNumber to set
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

/**
* Sets the website.
* @param website The website to set
*/
public void setWebsite(String website) {
this.website = website;
}

/**
* @param passwordHint The password hint to set
*/
public void setPasswordHint(String passwordHint) {
this.passwordHint = passwordHint;
}

/**
* @return Returns the updated version.
* @hibernate.version
*/
public Integer getVersion() {
return version;
}

/**
* The updated version to set.
* @param version
*/
public void setVersion(Integer version) {
this.version = version;
}

/**
* @return Returns the enabled.
* @hibernate.property column="enabled"
*/
public Boolean getEnabled() {
// isEnabled doesnt' work for copying properties to Struts ActionForms
return enabled;
}

/**
* @param enabled The enabled to set.
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}

public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;

final User user = (User) o;

if (username != null ? !username.equals(user.getUsername()) : user.getUsername() != null) return false;

return true;
}

public int hashCode() {
return (username != null ? username.hashCode() : 0);
}

/**
* Generated using Commonclipse (http://commonclipse.sf.net)
*/
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
// .append("roles", this.roles)
.append("firstName", this.firstName).append("lastName",
this.lastName)
.append("passwordHint", this.passwordHint).append("username",
this.username).append("fullName", this.getFullName())
.append("email", this.email).append("phoneNumber",
this.phoneNumber).append("password", this.password)
.append("address", this.address).append("confirmPassword",
this.confirmPassword).append("website", this.website)
.append("version", this.getVersion())
.append("enabled", this.getEnabled()).toString();
}

/**
* @return Returns the superAdmin property.
* @hibernate.property column="superadmin"
*/
public Boolean getSuperAdmin()
{
return superAdmin;
}

public void setSuperAdmin(Boolean superAdmin)
{
this.superAdmin = superAdmin;
}

/**
* Returns the user's roles for different projects
*
* @return Set
*
* @hibernate.set table="user_project_role" cascade="save-update" lazy="false" outer-join="true" fetch="join"
* @hibernate.collection-key column="user_id"
* @hibernate.collection-one-to-many class="com.testing.model.ProjectRole"
*/
public Set getProjectRoles()
{
return projectRoles;
}

public void setProjectRoles(Set projectRoles)
{
this.projectRoles = projectRoles;
}

public void addProjectRole(ProjectRole pRole)
{
this.getProjectRoles().add(pRole);
}

public void removeProjectRole(ProjectRole pRole)
{
this.getProjectRoles().remove(pRole);
}
}
----------------------------------------------------------------------

Thanks


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jan 29, 2006 2:54 am 
Senior
Senior

Joined: Tue Aug 23, 2005 8:52 am
Posts: 181
Yes, it looks like HibernateTemplate will close the Session if it(session) is not bound to the current thread of execution. So check if thats the case, and if not, make the Session be available for the entire thread of execution.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 15, 2006 6:51 am 
Regular
Regular

Joined: Fri Sep 17, 2004 10:51 am
Posts: 61
Location: Rimini, Italy
If you're using AppFuse, there's a help on
Matt Raible wiki about this.
Basically, your test should extend AbstractTransactionalDataSourceSpringContextTests.

This solved my problem, I hope it helps.

_________________
--
Marco


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 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.