【问题标题】:JPA sync validations before persisting持久化之前的 JPA 同步验证
【发布时间】:2016-12-14 18:22:34
【问题描述】:

我有以下问题。我有一个 AppointmentRequest 类,它是一个如下所示的实体:

public class AppointmentRequest implements Serializable{
    private static final long serialVersionUID = 4075310313280246558L;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence")
    @SequenceGenerator(name = "id_Sequence", sequenceName = "ID_SEQ")
    @Column(name = "APPOINTMENT_REQUEST_ID", nullable = false)
    private long requestId;
    @Version
    private long version;
    @Column(nullable=false)
    private String firstName;
    @Column(nullable=false)
    private String lastName;
    @Column(nullable = false)
    private long jmbg;
    @OneToOne
    private TimeSlot timeSlot;

时隙实体:

public class TimeSlot {
    @Id
    @Column(columnDefinition="TIMESTAMP(0)",nullable=false)
    private LocalDateTime dateTime;
    @OneToOne(mappedBy="timeSlot")
    private AppointmentRequest appointmentRequest;

这里是验证和持久化约会请求的 EJB 代码:

validator.slotAvailable(appointmentRequest.getTimeSlot());
entityManager.persist(appointmentRequest);

Validator EJB 检查时间段是否可用,如果是,则应保留约会请求,如果不是,则抛出异常。请求和响应通过 SOAP Web 服务进行,因此如果成功,服务返回 true,如果插槽已被预订,则返回 false。

当我一一发送 SOAP 请求时,一切正常。

但是,我制作了一个 SOAP 客户端,它可以创建多个线程(以模拟多个客户端)并同时为同一个时隙发送多个请求。在这种情况下,多个约会请求会在一个时间段中持续存在。 发生这种情况是因为验证是异步发生的,并且多个线程的验证同时通过,所以多个实体会被持久化,这是不应该发生的。

我该如何解决这个问题?通过向@Prepersist 回调添加验证,我获得了更好的性能,但有时多个约会请求仍会保留在同一时间段中。

【问题讨论】:

    标签: java hibernate validation jpa soap


    【解决方案1】:

    我只会同步并接受性能打击:

    validator.slotAvailable(appointmentRequest.getTimeSlot());
    
    synchronized {
      validator.slotAvailable(appointmentRequest.getTimeSlot());
      entityManager.persist(appointmentRequest);
      entityManager.flush()
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 2013-12-08
      • 1970-01-01
      • 2012-04-07
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      相关资源
      最近更新 更多