如何在Spring中从序列中生成实体字段的部分值?

huangapple 未分类评论47阅读模式
英文:

How to generate part of the value for entity field from sequence in Spring?

问题

我有一个名为"Product"的实体,大致如下所示:

@Entity
public class Product {
@Id
UUID id;

String productCode;
}
我希望productCode从一个名为Product_code_sequence的序列中生成,该序列已经存在于我的数据库中。在创建新的Product时,我希望从序列中获取下一个值,然后将其与一个String连接起来,以获得类似"PR000004"的结果。
此外,我希望解决方案是与数据库无关的,也就是说,我希望它可以在Postgres、H2和任何支持序列的其他数据库中运行。

英文:

I have an entity Product which looks something like this:

@Entity
public class Product {
@Id
UUID id;

String productCode;
}

I want productCode to be generated from a sequence called Product_code_sequence which is already in my database. When creating new Product, I want to get the next value from the sequence, and then concatenate it with a String to get something like "PR000004".
Also I want the solution to be database independent, meaning I want it to work with Postgres, H2 and any other database that supports sequences.

答案1

得分: 0

一旦您保存实体并保持在相同的事务上,您可以像这样设置属性(使用commons.lang3中的StringUtils):

product.setProductNumber(StringUtils.rightPad(String.valueOf(product.getId()), 5, '0'));

之后,您只需立即更新它:

repo.save(product);
英文:

As soon as you save your entity and remains on the same transaction, you can set your property like (using StringUtils from commons.lang3):

product.setProductNumber(StringUtils.rightPad(String.valueOf(product.getId()), 5, '0'));

right after you just update it:

repo.save(product);

huangapple
  • 本文由 发表于 2020年4月6日 20:35:31
  • 转载请务必保留本文链接:https://java.coder-hub.com/61060006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定