Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do hibernate mapping for table or view without a primary key [duplicate]

Possible Duplicate:
Hibernate and no PK

Anyone knows how to do hibernate mapping for table or view without a primary key?

like image 346
ariso Avatar asked May 21 '09 19:05

ariso


People also ask

Can Hibernate work without primary key?

No, Hibernate will not work without primary key. Every table should have some unique key. The mathematical definition of a relation is a set of tuples.

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.

Can we update primary key in Hibernate?

No. Hibernate doesn't allow to change the primary key. In general, a primary key value should never change, if needs to be changed than the primary key column(s) are not good candidate(s) for a primary key.


2 Answers

Don't think Hibernate allows mapping a table without a primary key...think about how Hibernate would perform updates without a column that can uniquely identify a row.

I guess a work-around would be to use a composite key with all columns, but you are much better off adding a primary key.

like image 198
Ryan Anderson Avatar answered Oct 22 '22 18:10

Ryan Anderson


I would do this only when you are reading data (not writing it). When you have a DB like oracle, you can have statements like

select DOKUMENT.*, ROWID from DOKUMENT

→ and thus, you can add this statement into the Hibernate mapping:

<id column="ROWID" type="string" />

subsequently, you define all other columns as

<property...

When you use the reverse engineering Wizard, you can

  1. remove the composite-key tag,
  2. search and replace key-property for property and
  3. insert above line
like image 36
Sebastian Rothbucher Avatar answered Oct 22 '22 18:10

Sebastian Rothbucher