JPA TABLE_PER_CLASS problems with ManyToOne
I have the following hierarchy
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Order {
...
@Entity
@Table(name = "b_order", schema = "public")
public class BOrder extends Order implements java.io.Serializable {
...
@Entity
@Table(name = "s_order", schema = "public")
public class SOrder extends Order implements java.io.Serializable {
I also have a class that Tr has references to both concrete subclasses
@Entity
@Table(name = "tr", schema = "public")
public class Tr implements java.io.Serializable {
...
private SOrder sOrder;
private BOrder bOrder;
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "s_order_id", nullable = false)
public SOrder getSOrder() {
return this.sOrder;
}
... same for BOrder
With the classes defined as above the lazy loading works fine:
Tr foundTr = trDAO.findById(trId);
// test lazy loading BOrder, SOrder
BOrder foundBOrder = foundTr.getBOrder();
SOrder foundSOrder = foundTr.getSOrder();
assertNotNull(foundSOrder);
assertNotNull(foundBOrder);
But if I try to execute a polymorphic query it doesn't work:
public List<Order> getOrdersByUId(Long uId) {
return (List<Order>) em.createQuery( //
" select o from Order o " //
+ " order by o.created desc ") //
.getResultList();
I get an error:
Order is not mapped
Based on this post: http://java.dzone.com/articles/jpa-implementation-patterns-mapping
BTW, when using Hibernate proxies, be aware that lazily loading a class mapped with any of the three strategies above always returns a proxy that is an instanceof the superclass. Blockquote
which matches the strange behavior I'm seeing.
However, this is where it gets weird. If I change the parent class to
@Entity
// @MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PE开发者_开发问答R_CLASS)
public abstract class Order {
that is I comment out the MappedSuperClass annotation, the polymorphic query works (creates the correct union). The problem is when I do that the LAZY loading from Tr to the two subclasses stops working.
Any ideas? Can I just use a native query to perform the union instead of JPA?
I'm using JPA 2.0 in JBoss 6.0.0 using Hibernate - whatever version ships with JBoss
There is nothing strange with failing to query MappedSuperClass. According JPA 2 specification:
2.11.2 Mapped Superclasses .... A mapped superclass, unlike an entity, is not queryable and must not be passed as an argument to EntityManager or Query operations. Persistent relationships defined by a mapped superclass must be unidirectional. ....
I filled the blanks in code you posted (without @MappedSuperClass) and both polymorphic query and lazy loading seem to work with Hibernate 3.5.6-Final. Maybe I made sometihing different way, what it comes to missing parts of code. Can you post even more compelete example?
精彩评论