EntityManager and Collections (Many-To-One relationship)

I have an entity (InvalidAddress) with a many to one relationship with another entity (ServiceRequest). I am trying to add an InvalidAddress entity to the InvalidAddressCollection owned by ServiceRequest

InvalidAddress invalidAddress =new InvalidAddress();

//perform setters on invalidAddress

invalidAddress.setServiceRequest(serviceRequest);

serviceRequest.getInvalidAddressCollection().add(invalidAddress);

entityManager.persist(invalidAddress);

I am getting a NPE because serviceRequest.getInvalidAddressCollection() is returning null when there are no related InvalidAddress entities. I know this makes sense but it seems like a waste to have to do this before I add any related entity to any collection

if (serviceRequest.getInvalidAddressCollection() ==null){

serviceRequest.setInvalidAddressCollection(new java.util.ArrayList();

}

serviceRequest.getInvalidAddressCollection().add(invalidAddress);

Is this very repetitive boiler-plate required when working with collections?

It would seem like the EntityManager should initialize the Collection and just return an empty list instead of a null list. Or is that up to me when I implement the getter on ServiceRequest?

Thanks for any advice.

[1497 byte] By [unobriania] at [2007-11-27 11:34:06]
# 1

Instead of adding it to the collection manually, why not just persist the Invalid Address? The collection should be updated by itself.

Example:

//Persist the address

InvalidAddress invalidAddress = new InvalidAddress();

invalidAddress.setServiceRequest(serviceRequest);

entityManager.persist(invalidAddress);

//now get the collection, it should have the invalid address in it.

ArrayList invalidaddresses = serviceRequest.getInvalidAddressCollection()

uvneta at 2007-7-29 16:55:22 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...