AtliB
AtliB

Reputation: 1273

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

Upvotes: 5

Views: 6417

Answers (2)

AtliB
AtliB

Reputation: 1273

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

Upvotes: 3

Lundberg
Lundberg

Reputation: 404

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.

Upvotes: 0

Related Questions