How to filter child entities collections with predicate? - jpa

I have an entity service on which I need to filter a collection of child entity, based on a list of id's. My service have a public method which receive the id of the parent entity and a list of id's of some of his children entities.
By default, I know that JPA will fetch all related entities and this his the actual behavior. But we need to work on the performance of the service. So instead of getting all related entities and filter them with many loop (filter on id's and also on other properties like date property), I want to get only entities concerned by my request.
My Parent entity
#Entity
#Table(name = "MyParent")
public class MyParentEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "SEQ_MyParent")
#SequenceGenerator(allocationSize = 1, name = "SEQ_MyParent",
sequenceName = "SEQ_MyParent")
#Column(name = "ID_PARENT")
private Long id;
#OneToMany(mappedBy = "myParent", cascade = CascadeType.ALL,
fetch = FetchType.EAGER, orphanRemoval = true)
private final List<MyChildEntity> myChild = new ArrayList<MyChildEntity>();
}
My Child Entity
#Entity
#Table(name = "MyChild")
public class MyChildEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "SEQ_MyChild")
#SequenceGenerator(allocationSize = 1, name = "SEQ_MyChild",
sequenceName = "SEQ_MyChild")
#Column(name = "ID_CHILD")
private Long id;
#ManyToOne
#JoinColumn(name = "ID_PARENT")
private MyParentEntity myParent;
}
I'm using Spring-data CrudRepository to get data from my DB and I also extends JpaSpecificationExecutor to use Predicate.
public interface MyParentRepository extends CrudRepository<MyParentEntity, Long>,
JpaSpecificationExecutor<MyParentEntity> {
}
This let me use CrudRepository findOne() method but with a Specification object instead of the regular Long parameter.
Also, I combine multiples Specification's object with the following call:
this.myParentRepository.findOne(Specifications
.where(firstSpecification(parentId))
.and(secondSpecification(childrenIdsList)));
I created a simple junit test with one Parent linked to two children entities. In my request, I'm able to get the parent entity with the provided Id. But even if I provide the child id, I always get both children entities in the list inside the parent.
In my method which return a new Specification object, in which the toPredicate method is override, I'm unable to create a Predicate that will filter my children collection and only get those one I'm interested. I know that the Hibernate Criteria has the possibility to add "Restrictions" but this is not available in the CriteriaBuilder that is provided with the toPredicate method.
public static Specification<MyParentEntite> firstSpecification(final Long id) {
return new Specification<MyParentEntite>() {
#Override
public Predicate toPredicate(Root<MyParentEntite> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate = cb.equal(root.get(MyParentEntity_.id), id);
return cb.and(predicate);
}
};
}
public static Specification<MyParentEntite> secondSpecification(final List<Long> ids) {
return new Specification<MyParentEntite>() {
#Override
public Predicate toPredicate(Root<MyParentEntite> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
Root<MyChildEntity> child = query.from(MyChildEntity.class);
Expression<Long> exp = child.get(MyChildEntity_.id);
Predicate p = exp.in(ids);
return cb.and(p);
}
};
}
In the secondSpecification() method, I also tried to use ListJoin instead of Root directly in the Entity. I searched in other questions here but it seems that this concern is solved with the Hibernate Criteria restrictions or with a LeftJoin, which I tried in my ListJoin in specifing JoinType.LEFT parameter.
Here are links to already tested solutions whitout success :
JPA CriteriaBuilder - How to use "IN" comparison operator
JPA2 Criteria-API: select... in (select from where)
I want to mention that I'm relatively new with Criteria API and Predicate. Maybe I'm missing something that is simple but that is obvious to experienced JPA developpers!
Thanks a lot for your help!

Finally, I found a way to resolved my issue. Requesting only partial collections of sub-entities is something that we found dangerous in terms of data integrity. If a remote service calls to request my parent entity with a partial collection of children's entities within a get, this parent entity object may be return for a modify operation which will result in many "delete" calls on the removed instances of children entities. The persistence API will consider these missing children as relations that were removed, which is something we don't want.
I created a dummy transfert object which contains the partial collections of children's entities requested so this dummy transfert object can't not be use in a future modify operation call. The full version of the parent entity will be used for the "modify" purpose.

Is your JPA provider hibernate?Have you considered the filters in hibernate which can filter the child entities instead of removing them.But the filter usage is somehow very difficult to understand!

Related

Why does JPA call sql update on delete?

Let´s assume these two entities:
#Entity
public class MyEntity {
#Id private String id;
#OneToMany(mappedBy = "myEntity", cascade = ALL) private Set<MyEntityPredecessor> predecessors;
}
#Entity
public class MyEntityPredecessor{
#Id private String id;
#ManyToOne(name = "entityID", nullable = false) private MyEntity myEntity;
#ManyToOne(name = "entityPre", nullable = false) private MyEntity predecessor;
}
When I try to call a delete with Spring Boot Data (JPA) with a MyEntity Instance, it will work some times (I see the select and then the delete statements in correct order), but sometimes it will try to run an update on the second entity trying to set the "entityPre" Field to null (even thoug it is set to nullable=falsE), causing the DB to send an error (null not allowed!! from DB constraint).
Strangely, this will happen at "random" calls to the delete...
I just call "myEntityRepository.getOne(id)", and then myEntityRepository.delete() with the result... There is no data difference in the DB between calls, the data structure has no null values when calling the delete method, so that should not be the reason.
Why is JPA sometimes trying to call updates on the Predecessor Table, and sometimes directly deleting the values? Am I missing something?
Add a similar ManyToOne annotated set to MyEntity which refers to the other non-nullable property, like:
#OneToMany(mappedBy = "predecessor", cascade = ALL) private Set<MyEntityPredecessor> other;
some explanation:
The issue doesn't happen randomly, but happen when you try to delete an entity which is linked to one (or more) MyEntityPredecessor via the predecessor property (which is mapped to the entityPre field)
Only the other field (entityID) is mapped back to the MyEntity object, so the deletion-cascade only happens via by that field.

JPA CriteriaQuery multiselect from several entities

Right now, I am using the method multiselect of CriteriaQuery to put some values from entity Termine in entity Task like this:
CriteriaBuilder builder = getEm().getCriteriaBuilder();
CriteriaQuery<Task> taskCriteria = builder.createQuery(Task.class);
Root<Termin> terminRoot = taskCriteria.from(Termin.class);
taskCriteria.multiselect(terminRoot.get("text"), terminRoot.get("empfaenger"), terminRoot.get("datVon"));
taskCriteria.where(builder.equal(terminRoot.get("empfaenger"), "000"));
List<Task> task = getEm().createQuery(taskCriteria).getResultList();
return task;
This is working fine, but now I am willing to gather the values text, empfaenger and datVon not only from the entity Termine but also from the entity Aufgabe, so that I will have a list of Tasks, that contains every Termin and Aufgabe which are having the same empfaenger.
Is it possible? If yes, how?
Thanks a lot in advance for your help!
I would derive both classes from task.
#Entity(name="Task")
#Inheritance(strategy = InheritanceType.JOINED)
#NamedQuery(name="Task.findAll", query="SELECT t FROM Task t")
public class Task {
#Id
Long id;
String text;
String empfaenger;
}
#Entity
public class Termin extends Task{
...
}
#Entity
public class Aufgabe extends Task{
...
}
And select them with a named query
List<Task> resultList = entityManager.createNamedQuery("Task.findAll",Task.class).getResultList();
or a criteria query with Task as Root.
This is the way I did to collect data from multiple entities (custom Select).
For example, multiple entities:
Root<InflowEntity> rootInflow = criteriaQuery.from(InflowEntity.class);
Root<OutflowEntity> rootOutflow = criteriaQuery.from(OutflowEntity.class);
You select the attributes you need from the above 2:
criteriaQuery.multiselect(rootInflow.get("inflowID"), rootInflow.get("name"),
rootOutflow.get("count"), rootOutflow.get("dateRange"));
Add the predicates (constraints) you need, for example:
Predicate[] predicates = new Predicate[2];
predicates[0] = criteriaBuilder.equal(rootInflow.get("uuid"), loginContext.getUuid());
predicates[1] = criteriaBuilder.equal(rootOutflow.get("uuid"), loginContext.getUuid());
Process the results:
criteriaQuery.where(predicates);
List<ResultsBean> results = session.createQuery(criteriaQuery).getResultList();
This Java bean (this is not the Hibernate entity), ResultsBean, stores the results. That is, it needs to have a constructor to accommodate the input the way the multiselect is arranged.

JPA and contains

I have a plain JPA Entity with the ID-Attribute generated:
#Entity(name = "AUTO_COMPLETION")
public class AutoCompletion extends AbstractEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "aip_seq")
#SequenceGenerator(name = "aip_seq", sequenceName = "aip_seq", allocationSize = 1)
#Column(name = "ID")
private Long id;
...
}
I create an JPA Entity:
AutoCompletion c2a1 = new AutoCompletion();
c2a1.setClient(c2);
c2a1.setText("c2a1");
c2a1.setType(AutoCompletionType.PERSON);
autoCompletionService.create(c1a1);
Create is implemented as follows:
#Override
public T create(final T t) {
this.em.persist(t);
return t;
}
Now the entity gets an written into the database along with the ID-Attribute set. I want to retrieve it again by a function:
List<AutoCompletion> completions = autoCompletionService.getAutoCompletions()
I thought I could call
completions.contains(c2a1)
but it always returns false... I don't understand why. Shouldn't it return true?
I would suggest to implement hashCode and equals
The object you created when you persist and the object retrieved will always not be the equal. Yes they are logically equal since they pertain to the same row in the DB, but they are different object references and point to different locations in memory.
See javadoc for List.contains. It uses equals method of your class to compare. Since you have not overriden the equals method, this will default obj1 == obj2 to operation, which will return true only if they point to the same location in memory.
You would get the same entity instance only if the calls were done in the same transaction. I guess that's not your case, you're calling service classes and you probably don't have a transaction scope bigger than service.
As others have already suggested, equals() an hashcode() need to be implemented in order for List#contains() to work like you expect it. This might or might not have consequences on the rest of your code, it should be analyzed.

JPA not updating ManyToMany relationship in returning result

Here are my entities:
#Entity
public class Actor {
private List<Film> films;
#ManyToMany
#JoinTable(name="film_actor",
joinColumns =#JoinColumn(name="actor_id"),
inverseJoinColumns = #JoinColumn(name="film_id"))
public List<Film> getFilms(){
return films;
}
//... more in here
Moving on:
#Entity
public class Film {
private List actors;
#ManyToMany
#JoinTable(name="film_actor",
joinColumns =#JoinColumn(name="film_id"),
inverseJoinColumns = #JoinColumn(name="actor_id"))
public List<Actor> getActors(){
return actors;
}
//... more in here
And the join table:
#javax.persistence.IdClass(com.tugay.sakkillaa.model.FilmActorPK.class)
#javax.persistence.Table(name = "film_actor", schema = "", catalog = "sakila")
#Entity
public class FilmActor {
private short actorId;
private short filmId;
private Timestamp lastUpdate;
So my problem is:
When I remove a Film from an Actor and merge that Actor, and check the database, I see that everything is fine. Say the actor id is 5 and the film id is 3, I see that these id 's are removed from film_actor table..
The problem is, in my JSF project, altough my beans are request scoped and they are supposed to be fetching the new information, for the Film part, they do not. They still bring me Actor with id = 3 for Film with id = 5. Here is a sample code:
#RequestScoped
#Named
public class FilmTableBackingBean {
#Inject
FilmDao filmDao;
List<Film> allFilms;
public List<Film> getAllFilms(){
if(allFilms == null || allFilms.isEmpty()){
allFilms = filmDao.getAll();
}
return allFilms;
}
}
So as you can see this is a request scoped bean. And everytime I access this bean, allFilms is initially is null. So new data is fetched from the database. However, this fetched data does not match with the data in the database. It still brings the Actor.
So I am guessing this is something like a cache issue.
Any help?
Edit: Only after I restart the Server, the fetched information by JPA is correct.
Edit: This does not help either:
#Entity
public class Film {
private short filmId;
#ManyToMany(mappedBy = "films", fetch = FetchType.EAGER)
public List<Actor> getActors(){
return actors;
}
The mapping is wrong.
The join table is mapped twice: once as the join table of the many-to-many association, and once as an entity. It's one or the other, but not both.
And the many-to-many is wrong as well. One side MUST be the inverse side and use the mappedBy attribute (and thus not define a join table, which is already defined at the other, owning side of the association). See example 7.24, and its preceeding text, in the Hibernate documentation (which also applies to other JPA implementations)
Side note: why use a short for an ID? A Long would be a wiser choice.
JB Nizet is correct, but you also need to maintain both sides of relationships as there is caching in JPA. The EntityManager itself caches managed entities, so make sure your JSF project is closing and re obtaining EntityManagers, clearing them if they are long lived or refreshing entities that might be stale. Providers like EclipseLink also have a second level cache http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching

Eclipselink performs an unexpected insert in a many-to-one relationship

I have a very basic relationship between two objects:
#Entity
public class A {
#ManyToOne(optional = false)
#JoinColumn(name="B_ID", insertable=false, updatable=true)
private StatusOfA sa;
getter+setter
}
#Entity
public class StatusOfA {
#Id
private long id;
#Column
private String status;
getter+setter
}
There's only a limited set of StatusOfA in DB.
I perform an update on A in a transaction:
#TransactionalAttribute
public void updateStatusOfA(long id) {
A a = aDao.getAById(123);
if(a != null) {
a.getStatusOfA().getId(); //just to ensure that the object is loaded from DB
StatusOfA anotherStatusOfA = statusOfADao.getStatusOfAById(456);
a.setStatusOfA(aontherStatusOfA);
aDao.saveOrPersistA(a);
}
}
The saveOrPersistA method is here merging 'a'.
I expect Eclipselink to perform only an update on 'a' to update the StatusOfA but it's executing a new insert on StatusOfA table. Oracle is then complaining due to a unique contraint violation (the StatusOfA that Eclipselink tries to persist already exists...).
There is no Cascading here so the problem is not there and Hibernate (in JPA2) is behaving as excepted.
In the same project, I already made some more complex relationships and I'm really surprised to see that the relation here in not working.
Thanks in advance for your help.
What does, statusOfADao.getStatusOfAById() do?
Does it use the same persistence context (same transaction and EntityManager)?
You need to use the same EntityManager, as you should not mix objects from different persistence contexts.
What does saveOrPersistA do exactly? The merge() call should resolve everything correctly, but if you have really messed up objects, it may be difficult to merge everything as you expect.
Are you merging just A, or its status as well? Try also setting the status to the merged result of the status.
Assumptions: #Id#GeneratedValue(strategy = GenerationType.IDENTITY)
Let's consider the following implementations of statusOfADao.getStatusOfAById(456) :
1. returns "proxy" object with just id set:
return new StatusOfA(456);
2. returns entity in new transaction:
EntityManager em = emf.createEntityManager();em.getTransaction().begin();
StatusOfA o = em.find(StatusOfA.class,456);//em.getReference(StatusOfA.class,456);
em.getTransaction().commit();
return o;
3. returns detached entity:
StatusOfA o = em.find(StatusOfA.class,456);//em.getReference(StatusOfA.class,456);
em.detached(o);
return o;
4. returns deserialized-serialized entity:
return ObjectCloner.deepCopy(em.find(StatusOfA.class,456));
5. returns attached entity:
return em.find(StatusOfA.class,456);
Conclusions:
Eclipselink handles only implementation N5 as "expected".
Hibernate handles all five implementations as "expected".
No analisys of what behaviour is jpa spec compliant