Is there a way to copy @id column generatedValue to another column of same entity?

我是研究僧i 提交于 2021-02-19 08:50:27

问题


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);  
}

回答1:


You can implement the same functionality in a different way. If you don't want to save the same object two times Then, first generating the sequence using @query annotation with a native SQL query on repository.

example

@Query(value = "SELECT cx_line_seq.NEXTVAL FROM DUAL", nativeQuery = true)
    public Long getCxLineId();

then setting the value to columns and saving them. if you are using above approach then you need to remove the sequence generator from your Entity class



来源:https://stackoverflow.com/questions/60713189/is-there-a-way-to-copy-id-column-generatedvalue-to-another-column-of-same-entit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!