• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate supports for PK

 
Charu Sama
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on a Hibernate Project and some of my database tables does not have Primary Key. I looked into Hibernate reference and could found how to handle a table which does not have PK on it. So, I am wondering if Hibernate supports table mapping without PK ???
Has anyone come across this situation ???
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Data in a database defined as an entity without a primary key is not relational data. So you will have problems using Hibernate (or any other ORM) with such data. The only fix is to correct your invalid entity relational model so everything has a primary key, ideally by adding surrogate keys.

If changing the ER model is not possible, the only workaround is to map your entities without primary keys so they have composite keys containing every attribute in the entity.
 
Arun Kumarr
Ranch Hand
Posts: 661
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Sturrock:
Data in a database defined as an entity without a primary key is not relational data. So you will have problems using Hibernate (or any other ORM) with such data. The only fix is to correct your invalid entity relational model so everything has a primary key, ideally by adding surrogate keys.

If changing the ER model is not possible, the only workaround is to map your entities without primary keys so they have composite keys containing every attribute in the entity.



Adding to it,
If your table(Table I) has a one-to-one mapping with another table(Table II), probably you can map the use the primary key's value of Table I as a foreign(but mapped like a primary key) in table II.

Eg;
Consider Table I and Table II.

Table I is an unique entity and can stand on its own. Table II is also unique but it always has a one-to-one relationship with table I. Table II is never related to any other model, apart from a business rule which says if table II is accessed it is always accessed with Table I.

Here it is upto you to decide whether you need to have a surrogate key for Table II, which doesn't have any business/Front end significance and just for facilitating the use of hibernate.

On the other side,
you can define something like this on your Table II.hbm file,





But, each of these approaches has it own advantages and disadvantages. You need to decide which suits your business best.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic