Hello i have got one entity which contains collection of object:
@Entity
public class ResourceType{
@Id
public Integer id;
@ManyToMany(mappedBy = "resourcesTypes")
private Set<Resource> resources = new HashSet<>();
}
As you see this entity contains collection of Resource
@Entity
public class Resource{
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "RESOURCE_TYPE_CROSS", joinColumns = { @JoinColumn(name = "RESOURCE_ID") }, inverseJoinColumns = { @JoinColumn(name = "RESOURCE_TYPE_ID", referencedColumnName = "ID") })
private List<ResourceType> resourcesTypes = new ArrayList<>();
}
So i guess if i get all resourceTypes with all resources this collection is in local cache.
But if i try persist resource :
@Override
public ResourcesDTO createResource(ResourcesDTO resource) throws CreateResourceException {
if (resource.getResourcesTypes().isEmpty()) {
throw new CreateResourceException("Can not create resouce " + resource.getName()
+ " none resource types is set");
resourceDAO.create(map(resource));
log.debug("Created resource: " + r);
resource.setId(r.getId());
return resource
}
If i perssist Resource with ResourcesTypes and next i will get all ResourceTypes entity manager do not found new Resources. But in my cross table resource_type_cross everything is ok. i will try to do something like that after create new resource:
for(ResourceType rt : resource.getResourceTypes()){
em.refresh(rt);
}
But its not working properly. After i will restart server everything is fine. But why entity manager do not refresh resource type ??
This is what i use to read all ResourceTypes:
public ResourceType getAllResourceTypes(){
em.createQuery("Select n from Resource n left join fetch n.children");
return em.find(ResourceType.class, 0); //0 - ROOT
}
as follow article : http://www.tikalk.com/java/load-tree-jpa-and-hibernate
The Main question is that : create or update entity by one side do not update another, so in my case i create and update resource type by resource entity, but i am using resouce type to get all resource.