Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA entity for a table without primary key

Tags:

java

jpa

I have a MySQL table without primary key, and I have to map it into a JPA entity. I cannot modify the table in any way.

Because entities must have a primary key, I have to specify one. If I'm certain that the field I use as a primary key in the entity (or the fields, should I opt for using composite primary key) will always be unique (and not null) in table, can the fact that the table doesn't have a primary key specified in CREATE TABLE cause any issues?

like image 928
tputkonen Avatar asked Jul 05 '10 11:07

tputkonen


People also ask

How do you make an entity without a primary key?

When you define an entity object, it must have a primary key or use a RowID attribute (based on the table's ROWID). To do so, you must create a new attribute while you are defining your entity object in the Entity Object Wizard.

Does JPA require primary key?

Every JPA entity must have a primary key. You can specify a primary key as a single primitive, or JDK object type entity field (see "Configuring a JPA Entity Simple Primary Key Field").

Can we have an entity without @ID?

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

Can we create entity in Hibernate without primary key?

No, Hibernate will not work without primary key. Every table should have some unique key.


2 Answers

That's correct. JPA has no way of knowing if the column(s) it is using as a PK is actually a real PK in the database. If those column(s) are, in practice, a PK, then it should be fine.

You may potentially get some performance problems if the pseudo-PK columns are not correctly indexed, though - JPA will execute queries against the PK on the assumption that it will perform well.

like image 62
skaffman Avatar answered Sep 20 '22 03:09

skaffman


JPA itself doesn't analyze your database. Just don't use common methods using primary key (find/merge/...) instead use named queries, for example using jpql update syntax.

@Entity
@Table(name = "login")
@NamedQueries({
        @NamedQuery(name = "Login.updateLastOnline", 
        query = "UPDATE Login l SET l.lastOnline = :newDate WHERE l.loginId = :loginId")
        })
public class Login implements Serializable
{

It doesn't matter if loginId is primary key

like image 33
Dewfy Avatar answered Sep 18 '22 03:09

Dewfy