@PreUpdate etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
@PreUpdate etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

8 Ağustos 2019 Perşembe

JPA @PreUpdate Anotasyonu - Lifecycle Callback

Giriş
@PrePersist,@PreRemove,@PostPersist,@PostRemove,@PostUpdate,@PostLoad anotasyonlarına da bakılabilir.

Açıklaması şöyle. Bu metod içinde kendi entity nesnesi hariç diğer nesnelere dokunmamalı deniliyor.
In general, the lifecycle method of a portable application should not invoke EntityMan ager or query operations, access other entity instances, or modify relationships within the same persistence context[46].[47] A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.
[46] Note that this caution applies also to the actions of objects that might be injected into an entity listener.
[47] The semantics of such operations may be standardized in a future release of this specification.
Örnek
Şu kod yanlış. Çünkü House nesnesi HouseInfo nesnesini değiştirmeye çalışıyor.
@Entity
@Table(name = "HOUSE")
public class House {

    @Id
    @Column(name = "ID")
    private long id;

    @OneToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "INFO_ID")
    private HouseInfo info;

    @PreUpdate
    protected void komplettiereEingabeWerte() {
        info.setCode("TEST");
    }

    //getters and setters
}

@Entity
@Table(name = "HOUSE_INFO")
public class HouseInfo {

    @Id
    @Column(name = "ID")
    private long id;

    @Column(name = "CODE")
    private String code;

    //getters and setters
}
Örnek - Yanlış
Şu kod yanlış. Parent nesnede yapılan güncelleme veritabanına yansımaz.
@PreUpdate
@PreRemove
@PrePersist
void updateParents() {
  Date now = new Date();
  BaseEntity container = getParent();
  while (Objects.nonNull(container)) {
    container.setUpdateDateTime(now);
    container = container.getParent();
  }
}
Açıklaması şöyle.
You are hitting a limitation of JPA (implementations).

When the event gets triggered the JPA implementation already decided which entities it is going to persist, thus your changes don't get picked up.