Reputation: 9065
I have a hibernate Entity with relationship mapping with fetch=FetchType.LAZY
Like:
....
private ConsumerEntity consumerEntity;
@ManyToOne(fetchType.LAZY)
@JoinColumn(name="orderId", insertable=false, updateable=false)
public ConsumerEntity getConsumerEntity(){
return this.consumerEntity;
}
....
And I want to transfer the entity object to HashMap<String, Object>
, I do that with Introspector
and currently just ignore the child-entities ,only parse the non-entity member to the map:
protected Map<String, Object> transBean2Map(Object beanObj){
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")
&& !key.endsWith("Entity")) {
Method getter = property.getReadMethod();
Object value = getter.invoke(beanObj);
map.put(key, value);
}
}
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE,"transBean2Map Error " + e);
}
return map;
}
I want to put every child-entities in the map as a embedded map, ONLY IF they were already fetched(maybe by explicitly invoking the getter() method or accidentally loaded by other method, giving bonus information when not bothering a lot will always a good idea, right?).
And NO, I don't want to make every thing as fetchType.EAGER
. Just want to detect if the child-entities are already loaded, then transfer and embedding them to the parent Map, otherwise, do nothing(won't query the db to fetch it).
Doing the embedding won't bother a lot, maybe just some recursions. So what I need is to know whether or not the child-entities are already loaded in the the parent entity, just like the consumerEntity
in the example above.
Is there any way I can do that?
Upvotes: 0
Views: 522
Reputation: 24433
Hibernate provides some tools for this, here is what you can try
if (HibernateProxy.class.isInstance(entity.getConsumerEntity())) {
HibernateProxy proxy = HibernateProxy.class.cast(entity.getConsumerEntity());
if (proxy.getHibernateLazyInitializer().isUninitialized()) {
// getConsumerEntity() IS NOT initialized
} else {
// getConsumerEntity() IS initialized
}
}
Upvotes: 3