本文介绍了有没有一种方法可以将@id列GeneratedValue复制到同一实体的另一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SpringBoot JPA服务中有一个要求,即该列的主键值必须存储在同一实体的另一列中.在下面的示例中, rowId StringPrefixedLineSequenceIdGenerator 生成.无论它生成什么值,我都需要将其存储在 lineId 列中.

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
}

问题是,直到 repo.save()之前,我无法使用 @id 的值.有没有办法从休眠会话或其他方法中获取generatedValue?还是可以使用 @GeneratedValue & @GenericGenerator 是否用于 @id 以外的列?我目前正在保存2次.我将用唯一值(输入中输入)保存新的CXline,然后再次进行更新,如下所示.感谢这里的任何输入.

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

推荐答案

您可以以不同的方式实现相同的功能.如果您不想两次保存同一对象然后,首先使用@query批注以及存储库上的本机SQL查询来生成序列.

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

示例

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

然后将值设置为列并保存.如果您使用上述方法,则需要从Entity类中删除序列生成器

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

这篇关于有没有一种方法可以将@id列GeneratedValue复制到同一实体的另一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:21