Home > database >  Update a certain field of an entity everytime before calling save()
Update a certain field of an entity everytime before calling save()

Time:04-21

So I have three entites. A, B and P (P is superclass). This is how they look like:

@MappedSuperclass
public class P {

    @Id
    @GeneratedValue
    protected Long id;

    protected LocalDateTime lastUpdated = LocalDateTime.now();
   
  //Other fileds, getters, setters, etc...
 
}

@Entity
@Table
public class A extends P {

  //fileds, getters, setters, etc..
 
}

@Entity
@Table
public class B extends P {

  //fileds, getters, setters, etc..
 
}

And I have repositories for both entities A and B

@Repository
public interface ARepository extends JpaRepository<A, Long> {

}

B repository

@Repository
public interface BRepository extends JpaRepository<B, Long> {

}

When I save an entity, I have to update the field lastUpdated by calling the setter method before save() everytime like so:

@Service
public class AService {
  
    private final ARepository aRepository;

    @Autowired
    public AService(ARepository aRepository){
        this.aRepository= aRepository;
    }

    public A doSomethingToA(A a){
        //Run some logic here...
        a.setLastUpdated(LocalDateTime.now()); // I dont want this line one very update method of every entity. is there a way to put it inside the save() method (overriding or something), or any other solution to this?
        return aRepository.save(a);
    }
}

The problem here is that if I have 200 entities that extend the class P, I have to call this setLastUpdated() method everytime before calling save(). Is there anyway I can put this line inside of the save method? (without having to override save on all 200 repositories of the 200 entites that extend P).

CodePudding user response:

You could use Hibernate's EntityListener on your class P :

public class P {

    @PreUpdate
    @PrePersist
    public void setLastUpdated() {
       lastUpdated = LocalDateTime.now();
    }
}

Official documentation about it : https://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/listeners.html

  • Related