How to persist the value returned by a method?

0

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

So 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 the value of it before saving, but would not be ideal, because if it is persisted by another class the programmer could forget to load the value of it.

But how would I persist the return of this method, or could I just implement it in the property's GET method?

But Hibernate works with the value of the property and not the field, how could this be changed for this situation?

    
asked by anonymous 05.11.2014 / 16:27

1 answer

2

I honestly do not see any gain with this approach, but since you want an exit for 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.

    
06.11.2014 / 17:34