0

I have an Entity with a generated value for invoiceNo:



@Getter
@Setter
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"invoiceId"}))
public class Invoice {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long invoiceId; //set format
    @Column( columnDefinition = "varchar(10) \n"
            + " GENERATED ALWAYS AS \n"
            + " (CONCAT('E', LPAD(invoice_id,8,'0'))) STORED ", insertable = false, nullable = false)
    private String invoiceNo;
    @Column(nullable = false, length = 70)
    private String customerName;
    @Column(length = 100)
    private String customerAddress;
    @Column(nullable = false, length = 15)
    private String contactNo; //set format
    @ManyToOne
    @JoinColumn(name= "userId", nullable = false, foreignKey = @ForeignKey(name = "FK_invoice_salesperson"))
    private User salesPerson;
    @Column(nullable = false, unique = true,length = 15)
    private String poNumber;
    @Column(nullable = false)
    private LocalDate purchaseDate;
    @OneToMany(cascade = CascadeType.PERSIST)
    @JoinColumn(name= "invoiceId", nullable = false)
    private List<InvoiceItem> invoiceItems;
    @Column(length = 100)
    private String remarks; 
    private Double totalAmount;
    @Column(insertable = true)
    @Enumerated(EnumType.STRING)
    private TransactionStatusEnums trxnStatus = TransactionStatusEnums.ACTIVE;
    @Column(nullable = false, updatable = false)
    @CreationTimestamp
    private LocalDateTime createdAt;

    
}

The issue is that the invoiceNo is always null when invoice entity is saved. I doubt it is because of updatable=false and insertable=false because other fields with that definition is fetched upon save.

As a workaround, I tried getting the new inserted invoice by Id using findById method but even that is returning invoiceNo field. But on findAll this field is populated.

NothingBox
  • 345
  • 5
  • 15
  • Does this answer your question? [JPA - Returning an auto generated id after persist()](https://stackoverflow.com/questions/9732453/jpa-returning-an-auto-generated-id-after-persist) – GreyBeardedGeek Nov 20 '22 at 18:49
  • Not really, since I can get the auto generated ID. I think the problem is only for the MySQL Generated value. Btw, I can get the invoiceNo if I call the findById in a separate API call. Really weird – NothingBox Nov 21 '22 at 01:30

0 Answers0