首页 > 解决方案 > 有没有办法将@id 列 generatedValue 复制到同一实体的另一列?

问题描述

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

@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
}

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

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

标签: hibernatespring-bootjpa

解决方案


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

例子

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

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


推荐阅读