How to create a foreign key in a Hibernate column on Integer

I have an object in Java, and I would like Hibernate to create a foreign key from the Integer field (since I have no reference to the object):

@Entity public class Invoice { ... @Column(nullable = true) private Integer generatedBy; ... 

I think I would 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 prefer not to maintain this relationship in a separate file (if possible).

+4
source share
2 answers

This does not seem to be a solution, therefore, taking it as an answer,

0
source

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

You can have your integer attribute, and the object attribute is displayed as follows:

 @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 cannot support external access to your generated ByUser field, it will only show sleep mode, that there is a connection. You can set the Integer field as you wish, when you load this object from the database later, you will have a link to the user.

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

0
source

Source: https://habr.com/ru/post/1344260/


All Articles