【问题标题】:Is there a way to copy @id column generatedValue to another column of same entity?有没有办法将@id 列 generatedValue 复制到同一实体的另一列?
【发布时间】:2020-06-27 23:47:52
【问题描述】:

我在 SpringBoot JPA 服务中有一个要求,其中列的主键值必须存储在同一实体的另一列中。在下面的示例中,rowIdStringPrefixedLineSequenceIdGenerator 生成。无论它产生什么价值,我都需要将其存储在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);  
}

【问题讨论】:

    标签: hibernate spring-boot jpa


    【解决方案1】:

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

    例子

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

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

    【讨论】:

    • 感谢 Shilanand。但我使用 SequenceStyleGenerator 为序列添加前缀。如果我删除序列生成器,我能做到吗?
    • 是的 DHR,只不过是分别获取序列,然后将其设置为主键(在您的情况下将其设置为 rowId 和 lineId)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多