10 Nisan 2023 Pazartesi

SpringData Persistable Arayüzü

Giriş
Şu satırı dahil ederiz
import  org.springframework.data.domain.Persistable;
Açıklaması şöyle. Böylece JPA sağlayıcısı belirtilen nesnenin durumu ile veri tabanındaki durumu senkronize etmeye çalışmaz. Yani kısaca nense için fazladan bir SELECT çalıştırmaz.
It enables us to instruct JPA that the entity that we are about to persist is new
Örnek
Şöyle yaparız
@MappedSuperclass
public abstract class AbstractPersistableEntity<T extends Serializable> 
        implements Persistable<T> {

  @Transient
  private boolean isNew = true;

  @Override
  public boolean isNew() {
    return isNew;
  }

  public void setNew(boolean isNew) {
    this.isNew = isNew;
  }

  @PostLoad
  @PostPersist
  void markNotNew() {
    this.isNew = false;
  }
}

@Entity
@Table(name = "employees")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Employee extends AbstractPersistableEntity<Integer> {

  @Id
  @Column(name = "emp_no")
  private int employeeId;

  @Column(name = "birth_date")
  private LocalDate birthDate;

  @Column(name = "first_name")
  private String firstName;

  @Column(name = "last_name")
  private String lastName;

  @Column(name = "hire_date")
  private LocalDate hireDate;

  @OneToMany(mappedBy = "employeeId", fetch = FetchType.EAGER, 
    cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<Salary> salaries;

  @OneToMany(mappedBy = "employeeId", fetch = FetchType.EAGER, 
    cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<Title> titles;

  @Override
  public Integer getId() {
    return employeeId;
  }
}
Şöyle yaparız
@Entity
@Table(name = "employees")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Employee extends AbstractPersistableEntity<Integer> {
  @Id
  @Column(name = "emp_no")
  private int employeeId;

  @Column(name = "birth_date")
  private LocalDate birthDate;

  @Column(name = "first_name")
  private String firstName;

  @Column(name = "last_name")
  private String lastName;
  ...

  @OneToMany(mappedBy = "employeeId", fetch = FetchType.EAGER, 
    cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<Salary> salaries;

  @OneToMany(mappedBy = "employeeId", fetch = FetchType.EAGER, 
    cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<Title> titles;

  @Override
  public Integer getId() {
    return employeeId;
  }
}

Hiç yorum yok:

Yorum Gönder