I had a similar problem with persistence provider eclipselink. I needed to add new orders from a client database with temporary "client orderIDs" to an existing customer in a server database. Because I needed the "server orderIDs" for further client requests, i wanted to create a map (clientID, serverID) and send it back to the client.
Basically my approach is to get a reference to the copy of the newly added child order. It will always be added to the end of my list in parent class customer, that fact is used to retrieve it.
I use the entity classes Customer and Order, where Customer has a List (LinkedList) of orders.
Parent Customer class:
...
@OneToMany(mappedBy = "customer", cascade=CascadeType.ALL, orphanRemoval = true)
private List<Order> orders = new LinkedList<Order>();
public Order getLastOrder() {
return orders.get(orders.size()-1);
}
Child Order class:
@ManyToOne(optional=false)
private Customer customer;
Servlet:
Customer customer = customerService.findByID(customerID); //existing customer
Order order = new Order();
//add attributes to new order
customer.addOrder(order);
customerService.update(customer); //generates keys for children
order = customer.getLastOrder();
Long orderID = order.getID; //Nullpointer exception
CustomerService updates customer with EntityManager.merge but I forgot to update the reference in the servlet:
CustomerService class:
public void update(Customer entity) {
entityManager.merge(entity);
}
I solved it this way:
CustomerService class:
public Customer update(Customer entity) {
return entityManager.merge(entity);
}
Servlet:
....
customer = customerService.update(customer); //generates keys for children
Now everything works fine.
@SequenceGenerator
the objects cascades just fine and returns with the new assigned id. – Anthony Accioly@GeneratedValue
. I am not a fan of pooled id's which I think is the reason why it works for Oracle/SequenceGenerator
– Ioannis Deligiannispersist
instead of merge. This the best solution so far, but being able to use merge and only cascadepersist
to new entities would be much better. – Ioannis Deligiannis