Question

I am getting a list of entities and attempting to add more values to it and have them persist to the data base... I am running into some issues doing this... Here is what I have so far...

Provider prov = emf.find(Provider.class, new Long(ID));

This entity has a many to many relationship that I am trying to add to

List<Organization> orgList = new ArrayList<Organization>();
...
orgList = prov.getOrganizationList();

So I now have the list of entities associated with that entity.
I search for some entities to add and I place them in the orgList...

List<Organization> updatedListofOrgss = emf.createNamedQuery("getOrganizationByOrganizationIds").setParameter("organizationIds", AddThese).getResultList();
List<Organization> deleteListOfOrgs = emf.createNamedQuery("getOrganizationByOrganizationIds").setParameter("organizationIds", DeleteThese).getResultList();
orgList.addAll(updatedListofOrgss);
orgList.removeAll(deleteListOfOrgs);

As you can see I also have a list of delete nodes to remove. I heard somewhere that you don't need to call persist on such an opperation and that JPA will persist automatically. Well, it doesn't seem to work that way. Can you persist this way, or will I have to go throught the link table entity, and add these values that way?

public class Provider implements Serializable {
@Id
@Column(name="RESOURCE_ID")
private long resourceId;
    ...
    @ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="DIST_LIST_PERMISSION", 
        joinColumns=@JoinColumn(name="RESOURCE_ID"),
        inverseJoinColumns=@JoinColumn(name="ORGANIZATION_ID"))
private List<Organization> organizationList;
    ...//getters and setters.
}

The link table that links together organizations and providers...

public class DistListPermission implements Serializable {
@Id
@Column(name="DIST_LIST_PERMISSION_ID")
private long distListPermissionId;

@Column(name="ORGANIZATION_ID")
private BigDecimal organizationId;

    @Column(name="RESOURCE_ID")
private Long resourceId;
}
Was it helpful?

Solution

The problem is that you are missing a cascade specification on your @ManyToMany annotation. The default cascade type for @ManyToMany is no cascade types, so any changes to the collection are not persisted. You will also need to add an @ElementDependent annotation to ensure that any objects removed from the collection will be deleted from the database. So, you can change your Provider implementation as follows:

@ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@ElementDependent
@JoinTable(name="DIST_LIST_PERMISSION", 
    joinColumns=@JoinColumn(name="RESOURCE_ID"),
    inverseJoinColumns=@JoinColumn(name="ORGANIZATION_ID"))
private List<Organization> organizationList;

Since your Provider class is managed, you should not need to merge the entity; the changes should take effect automatically when the transaction is committed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top