poniedziałek, 29 grudnia 2014

Hibernate annotations: many-to-one with custom column

Sometimes you need to create many to one relation that doesn't use primary key. For example:

|Foo|            |Bar|            
 ---------        -----------
|id (PK)  |      |id (PK)    |
 ---------        -----------
|bar_id   |----->|bar_id (UQ)|
 ---------        -----------
                 |bar_name   |
here Foo references Bar by bar_id not id (id is more like a record's id not Bar's id)...What you need to do is annotate attribute like that (this is Foo class):

    @JoinColumn(name="bar_id", referencedColumnName = "bar_id", nullable = false)
    private Bar bar;

If you want to have access to list of Foos from Bar you make something like this:

    @JoinColumn(name="bar_id", referencedColumnName = "bar_id")
    private Set<Foo> foos = new HashSet<>();

One more thing...if you have

<property name="hibernate.hbm2ddl.auto">create</property>

or "create-drop" you will probably get an error and there will be no foreign key added to table Foo. What you need to do is stop app change that prop:

<property name="hibernate.hbm2ddl.auto">update</property>

and start app again. This time there should be foreign key added to table. That's probably some sort of Hibernate bug.

Brak komentarzy:

Prześlij komentarz