tputkonen
tputkonen

Reputation: 5729

JPA entity for a table without primary key

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?

Upvotes: 10

Views: 20813

Answers (2)

Dewfy
Dewfy

Reputation: 23614

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

Upvotes: 2

skaffman
skaffman

Reputation: 403441

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.

Upvotes: 8

Related Questions