如何在 Hibernate 中的整数列上创建外键

发布于 2024-10-23 23:57:15 字数 441 浏览 4 评论 0原文

我在 Java 中有一个实体,我希望 Hibernate 从 Integer 字段创建外键(因为我没有对象引用):

@Entity
public class Invoice {

    ...
    @Column(nullable = true)
    private Integer generatedBy;
    ...

我想我想用属性做这样的事情:

    @ForeignKey(name="FK_Invoice_GeneratedBy", references="UserTable.UserId")
    @Column(nullable = true)
    private Integer generatedBy;

什么是实现这一目标的最佳方法是什么?我最好不必在单独的文件中维护这些关系(如果可能)。

I have an entity in Java and I would like Hibernate to create a foreign key from an Integer field (since I don't have an object reference):

@Entity
public class Invoice {

    ...
    @Column(nullable = true)
    private Integer generatedBy;
    ...

I think I'd like to do something like this with an attribute:

    @ForeignKey(name="FK_Invoice_GeneratedBy", references="UserTable.UserId")
    @Column(nullable = true)
    private Integer generatedBy;

What is the best way to achieve this? I would preferably not have to maintain these relationships in a separate file (if possible).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫七 2024-10-30 23:57:15

似乎没有解决方案,因此接受此作为答案。

There doesn't seem to be a solution to this, thus accepting this as an answer.

樱花细雨 2024-10-30 23:57:15

有一种方法可以做到这一点,但它不是很好...

您可以拥有整数属性,并且以这种方式映射对象属性:

@Column(ame = "GENERATED_BY", nullable = true)
private Integer generatedBy;

@ForeignKey(name="FK_Invoice_GeneratedBy")
@JoinColumn(name = "GENERATED_BY", nullable = false, updatable = false, insertable = false)
private User generatedByUser;

您可以不保留对 generatedByUser 字段的外部访问,它只会显示 hibernate是一种关系。您可以随意设置 Integer 字段,当您稍后从数据库加载此对象时,您将获得用户引用。

同样,不是很漂亮,但有时很有用。

There is a way to do it, but it is not very nice...

You can have your integer attribute, AND an object attribute mapped this way:

@Column(ame = "GENERATED_BY", nullable = true)
private Integer generatedBy;

@ForeignKey(name="FK_Invoice_GeneratedBy")
@JoinColumn(name = "GENERATED_BY", nullable = false, updatable = false, insertable = false)
private User generatedByUser;

You may keep no external access to your generatedByUser field, it will only show hibernate that there is a relationship. You can set the Integer field at will, when you load this object from DB later you'll have your user reference.

Again, not very pretty, but can be useful sometimes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文