id key 的自定义包装
我想将 id 包装在自定义类中。像这样
@Entity
@Table(name = "USERS")
public class User {
@EmbeddedId
UserId id;
}
@Embeddable
public class UserId implements Serializable {
private Long value;
}
UserId
自动生成 value
的问题。我应该怎么做才能使 value
上的 @GenerateValue
可行?
顺便说一句,如果 id 能够自动初始化,那就太好了。
I want to wrap id in custom class. Like this
@Entity
@Table(name = "USERS")
public class User {
@EmbeddedId
UserId id;
}
@Embeddable
public class UserId implements Serializable {
private Long value;
}
The issue in auto generation value
for UserId
. What I should do to make @GeneratedValue
on value
be workable?
BTW, It would be great if id
would be initialized automatically itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,Hibernate 只为标记为 @Id 的字段生成值。我发现 这篇 帖子,Hardy 的答案支持这一点。
我们尝试做类似的事情,并通过预插入侦听器对其进行管理。但它相当复杂且不理想。此外,您可能会发现不同数据库平台上的不同行为。使用 Oracle 序列意味着您需要在插入前分配值(Hibernate 执行选择来获取值,然后插入),但是使用 MySQL,自动递增字段将分配值,而 Hibernate 执行插入来生成自动生成的值value,然后选择以找出该值是什么。
As far as I know Hibernate only generates values for a field marked as the @Id. I found this post and Hardy's answer supports this.
We have tried to do similar and managed it via a pre-insert listener. It was fairly complex and non-ideal though. Also you might find different behaviour on different database palatforms. Using Oracle sequences would mean that you need to assign the value pre-insert (Hibernate does a select to get the value and then an insert) but with MySQL the auto incrementing field would assign the value and hibernate does an insert to generate the auto generated value and then select to find out what the value was.