JPA/hibernate inheritance and runtime type of an entity that subclasses an abstract super class/entity

StackOverflow https://stackoverflow.com/questions/12545494

문제

I would need some clarification about JPA/Hibernate inheritance.

Say I have an abstract Fruit entity that is subclassed by two Apple and Orange entities. Furthermore, I have an instance of Orange in database.

Can I retrieve this instance from database as a plain Fruit and cast it to Orange?

도움이 되었습니까?

해결책

Well you can do:

Fruit fruit = dao.get(id, Fruit.class)
if(fruit instanceof Orange)
{
   (Orange) fruit
}

and in runtime will be the appropriate type. But if you write a HQL you can check for its runtime type. This is usually unneeded if you are done your inheritance and mapping well.

select f from Fruit f where f.class = 'a.b.c.Fruit'

다른 팁

select f from Fruit f where treat(f as Orange).somePropetyInOrange=:value

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top