[英]Customizing JAX-RS response when a ConstraintViolationException is thrown by Bean Validation
[英]Why is JPA entity given an id by Spring Data JPA when ConstraintViolationException thrown (bean validation)
保存嘗試失敗( EntityManager
持續存在)使我的實體擁有一個ID。
就我而言,我將返回帶有錯誤消息的ConstraintViolationException
與原始實體一起返回的視圖。 該視圖檢查以查看實體是否具有ID,以將其包含在提交事件時所使用的表單操作網址中。 然后,控制器嘗試通過id加載實體。
在我的Spring MVC動作方法中的新未保存事件上運行此代碼時:
eventRepository.save(event);
並拋出一個異常(由ConstraintViolationException
引起),Spring的org.springframework.ui.Model
的事件實體現在包含一個ID! 為什么?
該EventRepository
使用從春數據JPA的exetends JpaRepository
:
public interface EventRepository extends JpaRepository<Event, Long> {}
這是Event
實體Bean的代碼段:
@Entity
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EVENT_SEQ")
@SequenceGenerator(name = "EVENT_SEQ", sequenceName = "ID_SEQ", allocationSize = 1)
private Long id;
@NotNull(message = "{event.proctor.null}")
@ManyToOne
@JoinColumn(name="PROCTOR_EMPLOYEE_ID")
private Employee proctor;
@NotNull(message = "{event.date.time.null}")
@Column(name="EVENT_DATE_TIME")
@Convert(converter = LocalDateTimePersistenceConverter.class)
@DateTimeFormat(pattern = "yyyy-MM-dd HHmm")
private LocalDateTime eventDateTime;
...
您可以在此處描述的JPA規范中找到事務回滾的行為。 想象一下,您在同一事務中執行兩項操作:
//begin transaction
em.persist(entity1);
em.merge(entity2);//here is thrown an exception
//commit transaction
在此示例中,符合JPA要求的是您在entity1中獲得一個ID,因為在事務回滾時merge()
即,當調用merge()
,entity1具有一個ID)。 還請注意,根據JPA,PersistentContext可能保持不一致狀態。 另外,請檢查perist()和merge()之間的區別( persist不返回任何內容,因為在該調用之后,entity1將得到管理)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.