Hibernate not loading associated object

i am trying to load a hibernate object ForumMessage but in it contain another object Users and the Users object is not being loaded.

My ForumMessage Mapping File:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Jan 4, 2011 10:10:29 AM by Hibernate Tools 3.4.0.Beta1 --> <hibernate-mapping> <class name="com.BiddingSystem.Models.ForumMessage" table="FORUMMESSAGE"> <id name="ForumMessageId" type="long"> <column name="FORUMMESSAGEID" /> <generator class="native" /> </id> <property name="ForumMessage" type="java.lang.String"> <column name="FORUMMESSAGE" /> </property> <many-to-one name="User" class="com.BiddingSystem.Models.Users" fetch="join"> <column name="UserId" /> </many-to-one> <property name="DatePosted" type="java.util.Date"> <column name="DATEPOSTED" /> </property> <many-to-one name="Topic" class="com.BiddingSystem.Models.ForumTopic" fetch="join"> <column name="TopicId" /> </many-to-one> </class> </hibernate-mapping>

and I am using the follwing code:

Session session = gileadHibernateUtil.getSessionFactory().openSession(); SQL="from ForumMessage"; System.out.println(SQL); Query query=session.createQuery(SQL); System.out.println(query.list().size()); return new LinkedList <ForumMessage>(query.list());

-------------Problems Reply------------

<many-to-one name="User" class="com.BiddingSystem.Models.Users" fetch="join" lazy="false">

I think you need to add lazy="false" as well.

You can add lazy="false" to the many-to-one mapping which will load the users when the ForumMessage is loaded. Alternatively you could initialize the users list using Hibernate.initialize(). Just make sure you do this before you close the session.

Session session = gileadHibernateUtil.getSessionFactory().openSession();
string sql = "from ForumMessage";
Query query = session.createQuery(sql);
List results = query.list()
for(ForumMessage message : results)
{
Hibernate.initialize(message.User);
}
return new LinkedList <ForumMessage>(results);

You should only do one of these though if you have a need to. Hibernate by default lazy loads objects to avoid unnecessary calls to the database. For example:

public LinkedList getMessages()
{
//It's assumed the session is opened and closed elsewhere.
string sql = "from ForumMessage";
Query query = session.createQuery(sql);
List results = query.list();
//The overhead of extra calls to the database occur here.
//This would have a similar impact if lazy load is set to false.
for(ForumMessage message : results)
{
Hibernate.initialize(message.User);
}
return new LinkedList <ForumMessage>(results);
}

public void printMessages()
{
LinkedList messages = getMessages();
for(ForumMessage message : messages)
{
System.out.println(message.ForumMessage);
}
}

In the above code sample the overhead is incurred for loading all the Users objects but those objects are never used. If Hibernate's lazy-loading were used then this extra overhead would not be incurred. In the following example the list of users isn't loaded until the list is used. This way calls are not made to the database until the data is actually needed.

public LinkedList getMessages()
{
//It's assumed the session is opened and closed elsewhere.
string sql = "from ForumMessage";
Query query = session.createQuery(sql);
List results = query.list();
return new LinkedList <ForumMessage>(results);
}

public void printMessages()
{
LinkedList messages = getMessages();
for(ForumMessage message : messages)
{
//Hibernate will load the users objects here when they are accessed.
for(Users user : message.User)
{
System.out.println(user);
}
}
}

One point to be careful of when lazy loading is all loading must be done in an active session. If you don't have an active session and you try and access something that has not yet been loaded Hibernate will throw a LazyInitializationException.

In addition, using Hibernate's lazy load functionality complies more with the idea of persistence ignorance where as using Hibernate.initialize() does not.

Category:java Views:0 Time:2011-01-05

Related post

  • HIbernate - bulk loading child objects 2011-05-18

    How can I get NHibernate to hook up child objects automatically or bulk load children rather than lazy loading for each parent? I have a large number of parent objects all of the same type. Each of them has two bags of child objects. As I need to loa

  • Hibernate lazy loading not working 2011-03-03

    I'm using version 3.6.1.Final I have the following property in my entity bean @JoinColumn( name = "FOLDER_PARENT_ID", referencedColumnName = "FOLDER_ID" ) @ManyToOne(cascade=CascadeType.MERGE, fetch= FetchType.LAZY ) private FolderTbl parent; In my u

  • How can we reduce the unnecessary loading of objects? 2009-08-17

    In hibernate as well as simple ORM strategy,i am normally loading all the values for the objects.Is there any way to avoid this. Due to this my app running slowly.. --------------Solutions------------- There are several ways to achieve this: Enable c

  • hibernate Lazy loading 2009-10-28

    my hibernate object A has object B, C, and D as properties : A.getB().getName(); A.getC().getTitle(); now, I want to load A with all its properties without getting a LazyInitializationException. so, I need to load A's object graph fully. is there any

  • Hibernate 2nd level cache objects that are lazy=false, result in a default fetch=join, is it documented anywhere? 2009-12-28

    I experience the following apparently undocumented issue, and I want to understand if I did something wrong Did anyone encounter the same issue? Is it really not documented anywhere? or did I miss something? The behavior is this Assume the following

  • Hibernate query cache - for objects not in the 2nd level cache - risky? useful? bad practice? 2010-01-04

    Related to this question Premise: These are my assumptions, based on my reading, experience and understanding, they may be wrong, if they are, please comment and I'll edit the question. Query cache is good mostly along with 2nd level cache Query cach

  • Converting Hibernate proxy to real object 2010-02-07

    During Hibernate session I am loading some objects and some of them are loaded as proxies due to lazy loading. It's all OK and I don't want to turn lazy loading off. But later I need to send some of the objects (actually one object) to the GWT client

  • nHibernate Lazy Load / Proxied Objects - Persistance Problems 2010-02-24

    [Updated with mapping files] Ran into an issue with a lazy loaded / proxied object being persisted today. It relates to two classes, Invoice and Address. A invoice has an Address property. Both classes are setup to be lazy loaded and all methods are

  • Hibernate lazy-load application design 2011-02-17

    I tend to use Hibernate in combination with Spring framework and it's declarative transaction demarcation capabilities (e.g., @Transactional). As we all known, hibernate tries to be as non-invasive and as transparent as possible, however this proves

  • Hibernate lazy loading and Hazelcast 2011-03-29

    we are using Hazelcast as Hibernate 2nd level cache now for a while but are recognizing long delays in storing and reading data when using more than one node. We make intensive use of composed objects and @OneToMany relations, and to increase perform

  • Delete item from collection in Hibernate without loading entities 2011-05-06

    I have three tables: user(id, name), group(id, name), xref_user_group(user_id, group_id) I have Two java classes: User { int id; String name; } Group { int id; String name; Set<User> users; } Can I delete user from group (and not deleting user)

  • dynamically lazy loading of objects does not work 2011-06-16

    I am using spring + hibernate in my project; I have two classes Reminder and Client in class reminder i have added a relationship of many to one for client and it is by default eagerly loaded. I want this Object graph most of the scenarios in my proj

  • Hibernate lazy loading requires EJB transaction? 2011-06-29

    When trying to optimize transactions on my java ee 6 project using hibernate, I tried to do as I did with Eclipselink and have transactions turned off for read-only queries, like follows: @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

  • Problem loading an object with 2 properties of the same class with NHibernate after saving from previous session 2011-09-09

    I have a Device class that I have defined that has 2 properties, LocalConnection and Connection, that are of the same defined class, Connection. Here is the Device class: [ComVisible(true)] [TypeConverter(typeof(ExpandableObjectConverter))] public cl

  • How does Hibernate keep track of object internally if no identifier is defined in the entity? 2012-02-16

    As per Hibernate reference doc The identifier property is strictly optional. You can leave them off and let Hibernate keep track of object identifiers internally. How does Hibernate keep track of object internally if no identifier is defined in the e

  • Hibernate session.load() not working with Java reflection getDeclaredFields? 2012-04-16

    I am running a function that loops through the declared fields, finds the difference between 2 instances of an object and outputs it (for audit trails). However, if I use an object loading from the hibernate session, I.E: HazardSubmission hs = (Hazar

  • Accessing lazy loaded entity object in Junit 2012-04-30

    I am trying to test a entity value in Junit, the entity has many-to-many relation with lazy fetch type. When I try to expand this in Junit I am getting the following error. Please hightlight if my understanding is wrong, all I need is to have the ses

  • org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session 2014-03-12

    I've an entity setup that looks like that: User <- (M:N) -> Project Project <- (1:n) -> WorkPackage WorkPackage <- (N:1) -> Category Using: Hibernate 4.3.4 Now I want to create a new User and assign a project to him with the followi

  • Displaying path/version information for a loaded COM object? 2008-10-07

    I've got some code that uses the Component Categories manager to load all of the classes that implement a particular category. Is there an easy way to get a description, path and version information from the loaded DLL or EXE? --------------Solutions

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.249 (s). 11 q(s)