hibernate - 有没有办法将@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);
}
解决方案
您可以以不同的方式实现相同的功能。如果您不想将同一个对象保存两次然后,首先使用 @query 注释和存储库上的本机 SQL 查询生成序列。
例子
@Query(value = "SELECT cx_line_seq.NEXTVAL FROM DUAL", nativeQuery = true)
public Long getCxLineId();
然后将值设置为列并保存它们。如果您使用上述方法,则需要从 Entity 类中删除序列生成器
推荐阅读
- python - 精确文本匹配 if 语句 python beautifulsoup
- docker - docker-compose up - 为容器设置环境变量
- shell - `screen` 的 `stuff` 命令是否使用 `stdin`?
- c# - 仅在调试器中来自 mscorlib 的 ArgumentNullException/PlatformNotSupportedException
- javascript - 为什么在与 Flat List 关联的 React Native 的 renderItem 函数中的 {} 括号中传递参数
- amazon-web-services - AWS::S3::NoSuchKey 指定的键不存在
- swift - 来自 AudioKit 的 sysex 接收的 MIDISystemCommand
- excel - 如果 1 列或两列都有单词,则输入文本
- javascript - @babel/register 中忽略的正确正则表达式模式是什么
- javascript - 在 next.js 中做路由的最佳方法是什么