简体   繁体   中英

JPA entity's collection members get detached or not managed

TGIF guys, but I am still stuck on one of my projects. I have two interfaces IMasterOrder and IOrder . One IMasterOrder may have a Collection of IOrder . So there can be several MasterOrder entity classes and Order entity classes who implements the interfaces.

To simplify the coding, I create IMasterOrder and IOrder objects everywhere, but when it needs to specify the concrete type then I just cast IMasterOrder object to the class type.

The problem is, this makes master class always return null about its orders. I am very curious about how JPA works with polymorphism in general?

Update

Sorry for the early confusion. Actually the question is much simpler

Actually the entity class is something like this

public class MasterOrder implements IMasterOrder {

// Relationships

@OneToOne(mappedBy = "masterOrder")
private OrderCustomFields customFields;

@OneToMany(mappedBy = "masterOrder")
private List<OrderLog> logs;

@OneToMany(mappedBy = "masterOrder")
private Collection<Order> orders;

// Fields...

And the finder method to get the Master order entity instance is like this

 public static MasterOrder findMasterOrder(String id) {
    if (id == null || id.length() == 0) return null;
    return entityManager().find(MasterOrder.class, id);
}

However, the MasterOrder instance from this finder method returns customFields and logs and orders which are all null. So how to fix this? Thanks in advance.

When you access logs and orders, is Master still a part of an active persistence context? ie: Has the EntityManager that found the Master Entity been closed or cleared? If yes, everything is working as expected.

For giggles, you could try changing the fetch attribute on logs and orders to EAGER ... this will help pinpoint if there is something else bad going on.

@OneToMany(mappedBy = "masterOrder", fetch = FetchType.LAZY)
private List<OrderLog> logs;

@OneToMany(mappedBy = "masterOrder", fetch = FetchType.LAZY)
private Collection<Order> orders;

Sounds like a problem with your mapping.. I don't think empty collections should be NULL, they should either be an empty list (if initialized), or a proxy that will be initialized when you read from it. If you leave the transaction and try to read from the collection, it SHOULD throw a lazy initialization exception. In either case, you should include all relevant classes in the question to provide further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM