How to persist the value returned by a method?

Asked

Viewed 59 times

0

In a class that has a collection, I need to persist the count of collection elements that follow a certain condition.

Therefore, I need to save the result of a method that checks all elements of this collection. Example:

class Group
{
   private List<Person> persons;

   @Column
   public getMarriedPersons()
   {
       int cont = 0;
       for(Person p : getPersons())
       {
           if(p.isMarried()){cont++;}
       }
       return cont;
   }
}

I could create a property and load its value before saving, but it would not be ideal, because if persisted by another class the programmer could forget to load the value of the same.

However it would have to persist the return of this method, or I could just implement it in the property’s GET method?

However the Hibernate works with the value of the property and not the field, would have to change this to this situation?

1 answer

2

I honestly don’t see any gain with this approach, but since you want a way out of this, use a method annotated with Prepersist.

@Entity
public class Entitidade() {
    private List<Pessoa> pessoaList;
    private Integer total;

    @PrePersist @PreUpdate
    public void prePersist() {
        // aqui vc faz o calculo
    }
}

Before entering or updating this method will be called and you will have the calculated value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.