Hibernate without Primary Key

前端 未结 5 1422
梦如初夏
梦如初夏 2020-12-03 08:00

I making a sample application with Hibernate. My requirement is that there is no primary key on the table. I had to do only select query from application. I know there shoul

相关标签:
5条回答
  • 2020-12-03 08:18

    So, modifying the table to add ID column does not see viable option.

    Why's that? Do you just mean, because it already has fifty thousand records? Trust me, that's really not very many.


    Even if the table doesn't have a surrogate key, and doesn't have a primary-key constraint, and even if you're not willing to alter the table, it still probably has some sort of candidate key — that is, some set of columns that are never null, and whose values uniquely identify a record. Even without altering the table to enforce their uniqueness and non-nullity, you can tell Hibernate that those columns form a composite ID.

    0 讨论(0)
  • 2020-12-03 08:22
    1. Hibernate requires that entity tables have primary keys. End of story.
    2. 50k records is simply not that many when you're talking about a database.

    My advice: add an autoincrement integer PK column to the table. You'll be surprised at how fast it is.

    0 讨论(0)
  • 2020-12-03 08:35

    Not with Hibernate. It requires a primary key.

    0 讨论(0)
  • 2020-12-03 08:38

    I have found solution for tables without primary key and null as values. It will work on oracle DB. Maybe something similar exists for other DBs.

    1. You should create new primary key in the POJO class:

      @Id @Column(name="id") private Integer id;

    and use createNativeQuery like this

    getEntityManager().createNativeQuery("select rownum as id, .....
    

    The native query will generate primary key and you will get unique results.

    0 讨论(0)
  • 2020-12-03 08:38

    Using DB2 with a table without primary keys the following works:

    Define the primary key field in the Entity similar to:

    @Id
    @Column(name="id")
    private Integer id;
    

    For Select Query add:

    String selectQuery = "select ROW_NUMBER() OVER () id, ..."
    

    I haven't tested with updates to the entity but selecting the info from the DB works fine

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