Hibernate Sequence卡在41值

时间:2018-05-31 15:25:44

标签: java hibernate spring-data-jpa

我班上有以下顺序 -

@Entity
public class CustomerOrder {

   @Id
   @SequenceGenerator( name = "CUSTOMER_ORDER_INVOICE_NO_SEQ_NAME", sequenceName = "CUSTOMER_ORDER_INVOICE_NO_SEQ", allocationSize = 20 )
   @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "CUSTOMER_ORDER_INVOICE_NO_SEQ_NAME" )
   private int id;

   private long orderInvoiceNo;

   //.. getters and setters

}

这是spring data jpa存储库类,具有获取next_val的方法

  @Repository
  public interface CustomerOrderRepository
    extends CrudRepository<CustomerOrder, Long>, JpaSpecificationExecutor<CustomerOrder> {

     @Query( value = "SELECT next_val FROM CUSTOMER_ORDER_INVOICE_NO_SEQ", nativeQuery = true )
     Long getNextOrderInvoiceNoSeq();
 }

我需要从序列中获取next_val并将该值传递给两个不同的位置。所以我调用我的存储库的getNextOrderInvoiceNoSeq()方法并将值存储为orderInvoiceNo -

@Autowired
private CustomerOrderRepository customerOrderRepository;

public void placeCustomerOrder( CustomerOrder customerOrder )
{

 long orderInvoiceNo = customerOrderRepository.getNextOrderInvoiceNoSeq();
 customerOrder.setOrderInvoiceNo(orderInvoiceNo);

 // using the same orderInvoiceNo to my other pojo
 // CustomerPurchase customerPurchase = new CustomerPurchase
 // customerPurchase.setOrderInvoiceNo(orderInvoiceNo);

 //....
 customerOrderRepository.save(customerOrder);
}


 @Entity
 public class CustomerPurchase {

   private String itemId;
   private long orderInvoiceNo;
   //.....     
 }

那么现在发生的事情是前两次放置customerOrder,我得到orderInvoiceNo为1和41,但之后每次我从序列中获得41作为next_val,因此每个订单都有相同的发票否41。

1 个答案:

答案 0 :(得分:1)

MySQL没有序列,因此在这种情况下,Hibernate将创建一个表生成器。

Hibernate将执行SELECT FOR UPDATE以获取最新的next_valUPDATE来增加值:

SELECT next_val as id_val 
FROM CUSTOMER_ORDER_INVOICE_NO_SEQ FOR UPDATE

UPDATE CUSTOMER_ORDER_INVOICE_NO_SEQ 
SET next_val= 2 where next_val=1

getNextOrderInvoiceNoSeq()只为最新值执行SELECT,但不会增加它。

那就是说,我不建议实施。最好switch to a native sequence并拥有foreign key CustomerOrder和CustomerPurchase。