-->
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.  [ 3 posts ] 
Author Message
 Post subject: Foreign table records not getting inserted
PostPosted: Sun Nov 07, 2010 2:23 pm 
Newbie

Joined: Fri Jul 11, 2008 11:39 pm
Posts: 7
Hi,

I have a User, UserRole and Role table. In my application, when i add a user, i must do so with a role. I have the following method on my dao class that does this:

public void addUser(User user, Role role) throws DALException
{
Transaction transaction = _session.beginTransaction();
try
{
UserRole userRole = new UserRole();
userRole.setPerson(user);
userRole.setRole(role);

Set<UserRole> userRoles = new HashSet<UserRole>();
userRoles.add(userRole);
user.setUserRoles(userRoles);

_session.save(user);

transaction.commit();
}
catch(Exception e)
{
transaction.rollback();
throw new DAOException(e);
}
}
}

The problem is, the User is added to the User table, but the UserRole table is blank. Can anyone explain to me why this does not work? Do you have to add each object individually or is hibernate smart enough to know that there are related records that need to be inserted as well?

Thanks


Top
 Profile  
 
 Post subject: Re: Foreign table records not getting inserted
PostPosted: Sun Nov 07, 2010 6:40 pm 
Senior
Senior

Joined: Fri Oct 08, 2010 8:44 am
Posts: 130
Hibernate is smart enough if you specify correct cascade type for particular field.


Top
 Profile  
 
 Post subject: Re: Foreign table records not getting inserted
PostPosted: Mon Nov 08, 2010 6:19 am 
Beginner
Beginner

Joined: Wed Jan 07, 2009 7:07 pm
Posts: 26
Use cascade in the mapping file for user roles and hibernate will automcatically save it for you. If it's a bidirectional relation also use inverse in userRole mapping.

Thanks
-Vishal


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