tags:

views:

29

answers:

2

I have the follow object:

@Entity
@Table(name="slideshow")
@Searchable
public class SlideShow implements Serializable {

    @Id
    @GeneratedValue(generator="slideShowSeq")
    @SequenceGenerator(name="slideShowSeq", sequenceName="slideshow_seq")
    @SearchableId
    int slideShowId

    @SearchableProperty
    String name

    @ManyToOne
    @JoinColumn(name = "userid", referencedColumnName="userid")
    User user

    @ManyToOne
    @JoinColumn(name = "eventid")
    Event event
...
}

eventId and userId are fks in slideshow table. By default User and Event should be lazy loaded to SlideShow by proxy. Hence, I should be able to get eventId and userId from slideShow.getEvent().getEventId() However, the eventId is null when I step through the proxy object in debugger. Same is true for userId.

Furthermore, if eventId and userId are available if I add

int eventId; 
String userId;

to the class. But that's kind of duplicating hibernate's function, right?

Am I missing something? Should the proxy object has the id of the associate object loaded lazily? How does one retrieve it? Thank you for all your help.

+1  A: 

If Event and User are being loaded lazily, then when you step through the proxy in a debugger then yes, the IDs of those referenced objects will not be there, because they haven't been loaded yet. Debuggers won't trigger the load process, they just examine the contents of the proxy. If you dig around with the debugger in the proxy enough, you'll probably find the ID in there somewhere, but it'll be part of Hibernate's internal representation of the proxy object.

If you actually invoke slideShow.getEvent().getEventId() programmatically, then the Event load should be triggered, and the ID made available. The ID is treated just like any other property in a lazily-loaded entity.

Do you actually need the ID of the referenced entity before it gets loaded?

skaffman
I want to get the id of referenced entity so I can call session.load to get the instance some where else in the code. Ideally, I would like to have object lazy loaded until there is a need. Then I get it from session cache. Hope I understand your question correct. Thank you for your help
JohnnyBeGood
A: 

If you're willing to depend on some Hibernate internals you can do something like:

if (event instanceof HibernateProxy) {
  eventId = ((HibernateProxy)event).getHibernateLazyInitializer().getIdentifier();
}
Brian Deterling