[英]Hibernate: EmbeddedId with auto increment
Suppose that I have a simple Hibernate entity with auto-incremented id.假设我有一个带有自动递增 ID 的简单实体 Hibernate。
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String name;
}
Is it possible to declare id
as a type-safe variable?是否可以将id
声明为类型安全变量? I could apply @EmbeddedId
like this.我可以像这样应用@EmbeddedId
。
@Entity
@Table(name = "product")
public class Product {
@EmbeddedId
private ProductId id;
private String name;
@Embeddable
public static class ProductId implements Serializable {
@GeneratedValue(strategy = IDENTITY)
private Long id;
public Long getId() {
return id;
}
}
}
It works with client-generated IDs, but not with database-generated ones.它适用于客户端生成的 ID,但不适用于数据库生成的 ID。
Has anyone solved similar problem?有没有人解决过类似的问题? What are the possible approaches?有哪些可能的方法?
First, you need to annotate ProductId class with @Embeddable like this:首先,您需要使用 @Embeddable 注释 ProductId class,如下所示:
@Embeddable
public static class ProductId implements Serializable {
private Long id;
private String name;
}
And, when you save entity, you need to create an instance of ProductId with unique parameters (in your case it is "name" field) as well.而且,当您保存实体时,您还需要创建一个具有唯一参数(在您的例子中是“名称”字段)的 ProductId 实例。
For more information, I suggest you to have a look at here有关更多信息,我建议您在 这里查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.