Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - Foreign keys instead of Entities

Currently, Hibernate allows me to load objects defined by *-to-one relationships directly with

entity1.getEntity2() 

Is it possible to get the foreign key instead of the object?

The current approach which I see is having addint to my mapping:

@JoinColumn(name="message_key") @ManyToOne(targetEntity=Message.class,fetch=FetchType.LAZY) private Message message;  //these lines currently exist  @Column(name="message_key") private Long message_fk; //the idea is to add those 2 lines 

Is there a better approach to get the foreign key, or is this the only one?

like image 954
iliaden Avatar asked Jun 10 '11 20:06

iliaden


People also ask

How do you make a foreign key a primary key in Hibernate?

You can use JPA's @MapsId annotation to tell Hibernate that it shall use the foreign key of an associated entity as the primary key. Let's take a look at a simple example. Each Book has a Manuscript, and each Manuscript belongs to 1 Book. The foreign key of the Book is also the primary key of the Manuscript.

What is foreign key in Hibernate?

In this post, we feature a comprehensive Example on Hibernate Foreign Key. Foreign key refers to single column or group of columns in table that link data present in another table through its primary key. A Foreign key can't exist without its parent key but viceversa is not true. Example – A Menu can have submenus.

How do you annotate foreign key in JPA entity?

Implementing With a Foreign Key in JPA. Note that we place the @OneToOne annotation on the related entity field, Address. Also, we need to place the @JoinColumn annotation to configure the name of the column in the users table that maps to the primary key in the address table.

Can we have an entity without @ID JPA?

An entity must always have a primary key; you cannot create an entity without a primary key (id).


2 Answers

Yes, you can do that. You just need to make it clear for hibernate which one is the mapping that it's supposed to maintain, like so:

@Column(name="message_key", updatable=false, insertable=false) private Long message_fk; 
like image 116
Affe Avatar answered Sep 22 '22 16:09

Affe


If you still want a reference to your entity but don't want to load it from the database just to get the foreign key, your approach is the correct one. Add insertable and updatabale = false to the Column attribute to prevent losing the correct reference to an entity.

@JoinColumn(name = "message_key") @ManyToOne(targetEntity = Messages.class, fetch = FetchType.LAZY) private Messages message;  @Column(name = "message_key", insertable = false, updatable = false) private Long message_fk; 
like image 39
Marcelo Avatar answered Sep 21 '22 16:09

Marcelo