2016-09-19 99 views
1

我正在創建一個簡單的彈簧應用程序,它應該在研討會中預定席位。比方說Booking類看起來像這樣JPA Hibernate Spring存儲庫確保事務在保存時完成?

@Entity 
@Table(name = "bookings") 
@IdClass(BookingId.class) 
public class Booking{ 
    @Id 
    private Long seminarId; 

    @Id 
    private String seatNo; 

    // .. other fields like perticipant info 

    // .. getter setters 
} 
當然

BookingId類:

public class BookingId implements Serializable{ 
    private static final long serialVersionUID = 1L; 
    private Long seminarId; 
    private String seatNo; 

    // .. constructors, getters, setters 
} 

而且我有一個repository

@Repository 
public interface BookingsRepository extends JpaRepository<Booking, BookingId>{ 
} 
控制器

當預訂請求到達時我第一次檢查如果已經存在具有相同seminer id和座位號的預訂,如果它不存在,我創建一個

@RequestMapping(method = RequestMethod.POST) 
public ResponseEntity<BaseCrudResponse> createNewBooking(@Valid @RequestBody NewBookingDao newBookingDao, BindingResult bindingResult){ 
    logger.debug("Request for a new booking"); 

    // .. some other stuffs  
    Booking newBooking = new Booking(); 
    newBooking.setSeminarId(newBookingDao.getSeminarId()); 
    newBooking.setSeatNumber(newBookingDao.getSeatNumber()); 
    // .. set other fields 
    Booking existing = bookingsRepository.findOne(new BookingId(newBooking.getSeminarId(), newBooking.getSeatNumber()); 
    if (existing == null) 
     bookingsRepository.save(newBooking); 

     return new ResponseEntity<>(new BaseCrudResponse(0), HttpStatus.CREATED); 
    } 

    return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); 


} 

現在,如果repositorysave方法沒有寫完commiting交易,另一個請求已經獲得過去存在檢查會發生什麼?有可能是不正確的預訂(最後一次提交將覆蓋以前)。這種情況是否可能發生?存儲庫是否確保在另一次保存呼叫之前完成交易?

也就是有沒有辦法告訴JPA拋出一些異常(IntegrityConstraintException如果複合鍵(在這種情況下seminerId和seatNumber)已經存在呢?現在在本設置其剛剛更新該行。

回答

1

你。可以使用javax.persistence.LockModeType.PESSIMISTIC_WRITE所以其他交易,只是得到了鎖無法更新該實體的一個

如果使用彈簧數據> 1.6,你可以註釋庫法@Lock:

interface BookingsRepository extends Repository<Booking, Long> { 

    @Lock(LockModeType.PESSIMISTIC_WRITE) 
    Booking findOne(Long id); 
} 

當然,您需要處理可能是控制器中的鎖定異常。

+0

所以可以說我有這種方法@Lock(LockModeType.PESSIMISTIC_WRITE) 預訂findOne(BookingId id);,只有在執行save()或findOne()之後纔會釋放鎖定? –

相關問題