Set Primary key and Foreign key on a single column in hibernate mapping having type String


#1

I have 2 tables - Request and SubRequest.

They both need to have a one-to-one mapping. In the SubRequest table I need to have the Primary Key and the Foreign key on the same column (which is RequestID) .

It is easily done in DB. My application uses Hibernate. So in the hibernate mappings file I need to do the same.

Also, the requirement is that this key must be a VARCHAR and generated by the application and not auto-generated by DB. I tried doing it from the following:

But all of these have the id as Integer and auto-generated.

I could not make it work for RequestID as String. Is it possible to do this in hibernate?


#2

Of course, it is possible.

I need to have the Primary Key and the Foreign key on the same column (which is RequestID) .

First, you need to use @MapsId as explained in this article.

Also, the requirement is that this key must be a VARCHAR and generated by the application and not auto-generated by DB.

Just remove the @GeneratedValue fro the @Id in the Request class:

@Id
@Column(name = "RequestID")
private String id;

And in the SubRequest entity you will have:

@Id
@Column(name = "RequestID")
private String id;

@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Reqeust request;

#3

Thanks Vlad. I tried using the following approach. But I am getting the following error-

ERROR: ORA-00904: “REQUEST_REQUEST_ID”: invalid identifier

This is coming when inserting a row in SubRequest table. It seems it is trying to find REQUEST_REQUEST_ID column instead of the REQUEST_ID. I found that hibernate is getting this column name by taking the @MapId variable name and appending it with the column name which we have given in the @Column. Ideally it should have just used the name mentioned in the @Column right?


#4

Try it like this and it will work:

@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "RequestID")
private Reqeust request;