0

I have a customer entity whose primary is a composite key. In the composite key one of the field is auto generated value.

@Entity
@AllArgsConstructor
@Builder
@Setter
@Getter
public class Customer {
 
  @EmbeddedId
  private CustomerId customerId;


  @Size(max = 255)
  @Column(name = "first_name")
  private String firstName;
@Embeddable
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class CustomerId implements Serializable {
  private static final long serialVersionUID = 8048935613697415032L;
  @NotNull
  @Column(name = "account_id", nullable = false)
  private Long accountId;

  @NotNull
  @Column(name = "id", nullable = false)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
}

When i use below snippet of code to save the customer, the record gets saved succesfully in db BUT fails to retrieve the saved.getCustomerId().getId() --> null. Any ideas to fix this?

@PostMapping
public ResponseEntity create(@RequestBody Customer sc,
                             @RequestParam long account_id) {
  sc.setCustomerId(CustomerId.builder().accountId(account_id).build());
  Customer saved = customerRepository.saveAndFlush(sc);
  return ResponseEntity.ok(saved);
}

Tried with EmbededdId/ IdClass. Both does not help

1 Answers1

0

As pointed out here: https://stackoverflow.com/a/66377401/9135271 you cannot use @GeneratedValue with @EmbeddedId.

You could use e.g. UUID for CustomerId_ID

    @NotNull
    @Builder.Default
    @Column(name = "id", nullable = false)
    private String id = UUID.randomUUID().toString();

Please note that @Builder.Default is required as you want to initialize CustomerId with CustomerId.builder().accountId(account_id).build()

P.S. I have to add @NoArgsConstructor to Customer to make your sample code working