I have the following sequence in my class -
@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
}
This is spring data jpa repository class having method to get 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();
}
I need to get the next_val from the sequence and pass that value to two different places. So I am calling the getNextOrderInvoiceNoSeq() method of my repository and storing the value as 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;
//.....
}
So what is happening now for first two iteration of placing customerOrder, I am getting orderInvoiceNo as 1 and 41, but after that each time I am getting 41 as next_val from the sequence, hence making each order having same invoice no which is 41.