JPA must has Primary Key

根據Java Persistence Book的23.6小節No Primary Key所述,使用JPA一定要有Primary Key
節錄內容如下

No Primary Key
Sometimes your object or table has no primary key. The best solution in this case is normally
to add a generated id to the object and table. If you do not have this option, sometimes
there is a column or set of columns in the table that make up a unique value. You can use
this unique set of columns as your id in JPA. The JPA Id does not always have to match the
database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically
when this occurs the data is read-only, so even if the table allows duplicate rows with the
same values, the objects will be the same anyway, so it does not matter that JPA thinks
they are the same object. The issue with allowing updates and deletes is that there is no
way to uniquely identify the object's row, so all of the matching rows will be updated or
deleted.

If your object does not have an id, but its' table does, this is fine. Make the object an
Embeddable object, embeddable objects do not have ids. You will need a Entity that
contains this Embeddable to persist and query it.

以上落落長原文,用中文簡述如下
1. 最好狀況,就是table有primary key(以下簡稱pk),object也有pk(object可想成JPA裡的Entity)
2. 次之狀況,就是table沒有pk,但有unique value,可以改用具備unique value的column或column set(多個column組合,類似複合鍵的感覺)
3. 如果table結構實在連column set都做不出pk,那就改用all column當pk;如果連all column當pk都會遇到資料重複的問題,那也不用擔心,因為這種資料結構通常都是read-only,但如果做update或delete的話,就會是整批同value一起做,object的反應會跟table一樣
4. 如果table有pk,object卻沒有(可能因為某些設計因素你不願提供),那就使用Embeddable object處理
(第4點的Embeddable object本人還不會,之後再細究)

沒有留言: