Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Error : The entity has no primary key attribute defined

Tags:

jpa

entity

I am using JPA in my application. In one of the table, I have not used primary key (I know its a bad design).

Now the generated entity is as mentioned below :

@Entity
@Table(name="INTI_SCHEME_TOKEN")
public class IntiSchemeToken implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="CREATED_BY")
    private String createdBy;

    @Temporal( TemporalType.DATE)
    @Column(name="CREATED_ON")
    private Date createdOn;

    @Column(name="SCH_ID")
    private BigDecimal schId;

    @Column(name="TOKEN_ID")
    private BigDecimal tokenId;

    public IntiSchemeToken() {
    }

    public String getCreatedBy() {
        return this.createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedOn() {
        return this.createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public BigDecimal getSchId() {
        return this.schId;
    }

    public void setSchId(BigDecimal schId) {
        this.schId = schId;
    }

    public BigDecimal getTokenId() {
        return this.tokenId;
    }

    public void setTokenId(BigDecimal tokenId) {
        this.tokenId = tokenId;
    }



} 

Here In my project, eclipse IDE shows ERROR mark(RED colored cross) on this class and the error is "The entity has no primary key attribute defined".

Can anyone tell me, How to create an entity without primary key ?

Thanks.

like image 238
Gunjan Shah Avatar asked Nov 02 '12 07:11

Gunjan Shah


2 Answers

You can't. An entity MUST have a unique, immutable ID. It doesn't have to be defined as a primary key in the database, but the field or set of fields must uniquely identify the row, and its value may not change.

So, if one field in your entity, or one set of fields in your entity, satisfies these criteria, make it (or them) the ID of the entity. For example, if there is no way that a user can create two instances in the same day, you could make [createdOn, createdBy] the ID of the entity.

Of course this is a bad solution, and you should really change your schema and add an autogenerated, single-column ID in the entity.

like image 200
JB Nizet Avatar answered Sep 17 '22 14:09

JB Nizet


If your Primary Key(PK) is a managed super class which is inherited in an entity class then you will have to include the mapped super class name in the persistence.xml file.

Look at the bug report: https://bugs.eclipse.org/bugs/show_bug.cgi?id=361042

like image 24
ChaitanyaBhatt Avatar answered Sep 20 '22 14:09

ChaitanyaBhatt