gpt4 book ai didi

java - Hibernate 序列卡在值 41

转载 作者:行者123 更新时间:2023-11-30 06:09:12 25 4
gpt4 key购买 nike

我的类里面有以下顺序 -

@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.

最佳答案

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

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

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客户订单和客户购买。

关于java - Hibernate 序列卡在值 41,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50627820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com