I have a requirement in SpringBoot JPA service where the primary key value of the column must be stored in another column of same entity. In example below, rowId is generated by StringPrefixedLineSequenceIdGenerator. Whatever value it generates, I need to store the same in lineId column.
@Entity
@Table(name="CX_LINE")
public class CXLine {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cx_line_seq")
@GenericGenerator(
name = "cx_line_seq",
strategy = "com.tmo.chub.entity.generator.StringPrefixedLineSequenceIdGenerator"/*,
parameters = {@Parameter(name = StringPrefixedLineSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "2-XP-"),
@Parameter(name = StringPrefixedLineSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%04d")}*/)
@Column(name="row_id")
private String rowId;
@Column(name="LINE_ID")
private String lineId;
//getters & setters
}
The issue is, the value of @id will not be available to me until the repo.save(). Is there a way to get the generatedValue from hibernate session or something? or Is it possible to use @GeneratedValue & @GenericGenerator for columns other than @id?
I am currently doing 2 saves. I will save the new CXline with unique value (coming in input) and then do the update again like shown below. Appreciate any inputs here.
CXLine existingLine = lineRepo.findByExtLineId(payload.getCustomerProfile().getCustomerId());
if(existingLine !=null){
//do update
}
else{
CXLine newLine = new CXLine();
newLine.setLineId(payload.getCustomerProfile().getCustomerId());
// set other columns
lineRepo.save(newLine);
CXLine lineToUpdateLineId = lineRepo.findByExtLineId(payload.getCustomerProfile().getCustomerId());
lineToUpdateLineId.setLineId(lineToUpdateLineId.getRowId());
lineRepo.save(newLine);
}