简体   繁体   中英

How to create foreign key in Hibernate on Integer column

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).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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