Create a One-to-Many GAE JPA DataNucleus Object

Say the owner has a collection of Watch (s).

I am trying to create Watches and add the created watches to the existing collection of owner watches (arraylist).

My method is as follows:

public void add(String ownerName, String watchName) { Owner o = new OwnerDAO().retrieve(ownerName); //retrieves owner object without fail EntityManager em = EMF.get().createEntityManager(); EntityTransaction t = em.getTransaction(); Watch w = new Watch(watchName); Owner owner = em.merge(o); t.begin(); owner.getWatches().add(w); t.commit(); em.close(); } 

The code works in the local GAE environment without problems, but posed the following problem when it is in the GAE online environment:

org.datanucleus.store.mapped.scostore.FKListStore$1 fetchFields: Object " package.Owner@2b6fc7 " has a collection "package.Owner.watches" yet element " package.Watch@dcc4e2 " doesnt have the owner set. Managing the relation and setting the owner org.datanucleus.store.mapped.scostore.FKListStore$1 fetchFields: Object " package.Owner@2b6fc7 " has a collection "package.Owner.watches" yet element " package.Watch@dcc4e2 " doesnt have the owner set. Managing the relation and setting the owner .

Can I find out how I can solve this problem? Thanks!

Objects:

Owner:

 @id private String name; @OneToMany(mappedBy = "owner", targetEntity = Watch.class, cascade = CascadeType.ALL) private List<Watch> watches= new ArrayList<Watch>(); 

Clock:

 @id private String name; @ManyToOne() private Owner owner; 

Thank you in advance!

Best wishes,

Jason

+4
source share
1 answer

Your connection is bidirectional, but you are not setting both sides of the channel correctly as reported by the error message. Your code should be:

 ... owner.getWatches().add(w); w.setOwner(owner); //set the other side of the relation t.commit(); 

A typical example is the use of security link management techniques to properly set both sides of an association like this (in Owner ):

 public void addToWatches(Watch watch) { watches.add(watch); watch.setOwner(this); } 

And your code will be as follows:

 ... owner.addToWatches(w); t.commit(); 
+3
source

All Articles