새로운 Entity인지 판단하는 방법 #127
Replies: 3 comments
-
JPA에서 특정 엔티티가 새로운 엔티티인지 판별하기 위해서는 다음과 같은 방법을 사용할 수 있습니다.
EntityManager의 contains 메서드를 사용하여 해당 엔티티가 현재 영속성 컨텍스트에 포함되어 있는지 확인할 수 있습니다. 새로운 엔티티는 영속성 컨텍스트에 포함되지 않으므로 false를 반환합니다. @Autowired
private EntityManager entityManager;
public boolean isNewEntity(Object entity) {
return !entityManager.contains(entity);
}
만약 엔티티의 식별자를 개발자가 임의로 수동 할당하지 않는 경우라면,
@Entity
public class MyEntity implements Persistable<Long> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
....
@Override
public boolean isNew() {
return id == null;
}
}
@Entity
@EntityListeners(MyEntityListener.class)
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
....
}
public class MyEntityListener {
@PrePersist
public void prePersist(MyEntity entity) {
// 새로운 엔티티가 영속화되기 전에 호출됨
System.out.println("새로운 엔티티 입니다.");
}
} |
Beta Was this translation helpful? Give feedback.
-
새로운 Entity인지 여부는 JpaEntityInformation의 다른 설정이 없으면 JpaEntityInformation의 구현체 중 JpaMetamodelEntityInformation 클래스가 동작합니다.
키 생성 전략을 사용하지 않고 직접 ID를 할당하는 경우 새로운 entity로 간주되지 않습니다. |
Beta Was this translation helpful? Give feedback.
-
.
Beta Was this translation helpful? Give feedback.
All reactions