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?
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.
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.
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.
An entity must always have a primary key; you cannot create an entity without a primary key (id).
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With