英文:
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);
专注分享java语言的经验与见解,让所有开发者获益!
评论