简体   繁体   English

有人知道在保存之前如何通过序列和任何其他属性与 spring jpa 生成连接 ID 吗?

[英]Someone knows how concatenate id generate by sequence and any other property with spring jpa before to save?

Image that this is an entity with full structure well defined图像,这是一个结构完整且定义明确的实体

public class Entyty{
//genarate by sequence
private Long id;
//value coming from request
private String value;
//I need concatenate this value with id + value before to save in db
private String composeValue;

}

someone knows how to do it?有人知道怎么做吗?

You can't do it with the normal JPA process.你不能用正常的 JPA 进程来做到这一点。

The reason is rather obvious: The id only gets generated when the entity gets saved.原因很明显:只有在保存实体时才会生成 id。

So you either have to make your requirement more lenient or manually assign the id.因此,您要么必须使您的要求更加宽松,要么手动分配 id。 It might still come from a sequence if that is important to you.如果这对您很重要,它可能仍然来自一个序列。

So here are some variants that might be helpfull:因此,这里有一些可能有用的变体:

  1. Generate the id manually.手动生成 id。 You could select the next value for a sequence from the database using a normal SQL query and use it to set the id of any new entity.您可以使用普通的 SQL 查询 select 数据库中序列的下一个值,并使用它来设置任何新实体的 id。 You can then use normal java code to concatenate it with another property.然后,您可以使用普通的 java 代码将其与另一个属性连接起来。

  2. You can have a getter only that will take the id and the other property concatenate them and return the result.您只能有一个获取 id 的 getter,其他属性将它们连接起来并返回结果。 Once the property and id are set the getter will return the correct result.一旦设置了属性和 id,getter 将返回正确的结果。 Before that not so much.在此之前没有那么多。

  3. You can populate the field in the database using a trigger.您可以使用触发器填充数据库中的字段。 If you want you may select the extra field or just keep it in the database.如果你愿意,你可以 select 额外的字段或将其保存在数据库中。

  4. Instead of using a trigger you can use a view and have the view assemble the extra field.您可以使用视图并让视图组装额外的字段,而不是使用触发器。 If you use it in where clauses or similar you may put a function based index on it.如果您在 where 子句或类似条款中使用它,您可以在其上放置基于 function 的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM