Lessons Learnt: Hibernate JPA and the @Id annotation
Today we came across some very interesting behaviour with the Hibernate JPA provider.
We had a read-only entity which was a DTO (we use of primarily for returning data from multiple tables via native queries). We had just implemented some enhancements to our code base, but failed to notice that our key column no longer met the requirements of a primary key, well until our unit tests started failing.
What happened? Well, we discovered that when issuing a query that returned multiple records, Hibernate after it loaded the first record would use its value to populate any other instances of the entity within the result set which had that key.
For example:
For a Person entity with name and social security number (social security number being the primary key), if we had a query that returned a list/collection of Person entities, any ssn occurring in the list more than once would produce identical records.
Bearing in mind the definition of primary keys, this behaviour is expected and normal. I was still surprised, however, seeing as I already mentioned that our use case was not necessarily a regular entity and that we only had the annotation there because the JPA spec requires it.
My question: shouldn't query-only uses for journal-like data be supported in JPA? Is this just one of the scenarios that the JPA spec wasn't built to deal with? Kindly share your best practices for dealing with scenarios like these.
