| You just detach the object if you see it's a proxy. Though that requires that you update all entities referencing the old object. You'd need something like this
someObject.setToOne(em.getReference(BaseClass.class, 1L));
BaseClass o = em.find(BaseClass.class, 1L);
if (!org.hibernate.Hibernate.isInitialized(o)) {
em.detach(o);
o = em.find(BaseClass.class, 1L);
someObject.setToOne(o);
}
I'm not sure it is a good idea to actually do a query for checking the type, as it might not actually be required. When you call EntityManager.find() Hibernate doesn't know if the concrete subtype is relevant to you. What would it help you if you got a warning message when calling find vs. getting an exception when casting to a subtype? The cast would fail either way. As I said, I don't think it's a good idea that getReference runs an actual query. If a query happens later because you access a propery, that's a different story, but the getReference call itself just shouldn't. You already acknowledge that you have to take special care when working with polymorphic entities, so maybe you should just always use em.find for polymorphic entities or handle proxies properly as I presented. Another option I can think of is mapping the table multiple times, assuming you're not using table per class inheritance. Map it once without polymorphism and mark it as read only, having just an id property and once the way you have it right now. When you refer to it in an entity like the one where you use getReference for, use the type with just the id. That way, the 1LC won't bite you. |