JPA entity has no primary key?

前端 未结 5 760
灰色年华
灰色年华 2020-12-16 13:36

I have an Entity class:

@Entity
@Table(name=\"CMC_MAP_SERVER_INFO\")
@NamedQuery(name=\"CmcMapServerInfo.getMapServer\", query=\"SELECT c FROM CmcMapServerIn         


        
相关标签:
5条回答
  • 2020-12-16 14:11

    You can mark the applicationName or the ip address as the primary key (though not auto generated). It's ok even if neither of these columns are declared as primary keys in the database.

    0 讨论(0)
  • 2020-12-16 14:12

    JPA 2.0 Specification

    • Entity class must be annotated with the Entity annotation.
    • Entity class must have a no-arg constructor.
    • Entity class must not be final
    • Entity class must implement the Serializable interfaces.
    • Entity class must have a unique, immutable ID

    Otherwise, you cannot.

    0 讨论(0)
  • 2020-12-16 14:22

    I had this problem as well with a message without PK.

    In Oracle, you can use the ROWID column which is always there for any table.

    Like this:

    @Id
    @Column(name="ROWID")
    String rowid;
    

    Hope it helps...

    0 讨论(0)
  • 2020-12-16 14:22

    Another way would be specify that the class itself can be used as unique identifier with @IdClass. So in this case just annotate the class with @IdClass(CmcMapServerInfo.class) and it should be independent of underlying database.

    0 讨论(0)
  • 2020-12-16 14:24

    Every entity object in the database is uniquely identified. An alternate way to represent a table without a primary key is to use a composite primary key using all its columns, or some of them representing a candidate key:

    @Entity
    public class TableWithoutId {
        @EmbeddedId EmbeddableTableWithoutId id;
    
        /* Getters an Setters... */
    
        //Here you can implement @Transient delegates to the Getters an Setters of "id".
    }
    
    @Embeddable
    Class EmbeddableTableWithoutId {
        int columnA;
        long columnB;
        /* Getters an Setters... */
    }
    

    Maybe you will have problems with [Select By Id]:

    entityManager.find(TableWithoutId.class, id);//it can throws NonUniqueResultException or anything like that...
    

    Take care and be happy!!!

    0 讨论(0)
提交回复
热议问题