1

I am using Spring+HibernateDAO and want to access a table which does not have a primary key. Because Hibernate requires that entity tables have primary keys. ,I need to create some virtual primary key(perhaps), just to fool hibernate (it satisfies with @Id only) Or doing any efforts on database side without touching existing table is also fine. Please suggest any workaround which does NOT require ALTER EXISTING TABLE , any other table inheritance/structure changes are welcome.

PS. Already using JDBC template with manual mapping of columns to custom object.DB is Sybase ASE15 if it matters.

Sankalp
  • 2,030
  • 7
  • 30
  • 41
  • Have you looked at composite primary keys with hibernate? Hopefully there are a set of columns that are unique. If so map those as a composite key. – neildo Feb 05 '14 at 05:44
  • @neildo Yes I already tried considering that, but because of type of data in the table and manner its already being used can not use it. – Sankalp Feb 05 '14 at 06:15
  • 1
    If you ONLY want to use Hibernate to SELECT from this table, you could use a native query to populate a non-managed entity: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#d0e13904 If you want Hibernte to manage INSERT/UPDATE/DELETE then you are out of luck. You must have an ID. Identity is a core aspect of Hibernate's entity management. – neildo Feb 05 '14 at 06:56
  • Yes you are right @neildo . As my requirement dont include Updates this Idea works for some extent. The reason for only some extent is like :- `q.setResultTransformer(Transformers.aliasToBean(Y.class)); ` but this fails with: org.hibernate.PropertyNotFoundException: Could not find setter for some_property. X has a field called someProperty with the appropriate getter and setter but in this case it doesn't seem like Hibernate maps the column name (some_property) to the correct field name. Agree its a good idea but ,I will let the question still open as perhaps we may get more featured solution. – Sankalp Feb 05 '14 at 09:45

1 Answers1

1

There are some many answers to your question on stack-overflow itself, I am surprised, you didn't find one :P

How to work with tables without PRIMARY KEY in Hibernate?

Hibernate and no PK

Hibernate without Primary Key

This one on CodeRanch

Analyse and make your choice :)

Community
  • 1
  • 1
DarkHorse
  • 2,740
  • 19
  • 28
  • @DarkHorrse Yes the solution 'Hibernate and no PK' works. Actually I just read it too literraly which was mentioned in your third reference earlier ` Hibernate requires that entity tables have primary keys. End of story. ` But you have got the correct way there in Second Solution. Tons of thanks :) – Sankalp Feb 05 '14 at 12:41