Search code examples
javaspringentity-frameworkjpatransient

Automatically assigning value to transient attribute


I am using @Entity from javax.persistence.Entity to create my entities and in this particular case I had to create a transient attribute (private Boolean assigned;) and I am using PagingAndSortingRepository from org.springframework.data.repository to create interfaces to manage my database entities.

I need to assign this value (Boolean assigned) when a List (OneToMany) attribute is empty, so I am doing it programatically using an if clause, the problem is I have to write that if clause everywhere and I would like to know if it is possible to auto-assign that variable somehow.

Thanks in advance.


Solution

  • If you need to set the value of this flag before being persisted in the database, I would recommend use entity listener @PrePersist, basicallu give you the possibility to execute certain logic before you persist the object, in the method you could check if the Array is empty and set the value to false. There are other events such as:

    @PostLoad Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.

    @PostLoad
    public void setAssigned() {
       //Your logic for set to true or false the transient variable.
    }
    

    I think this is one option to do the logic in only one place at be managed by the provider. Read more about it here