Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a database view without a primary key when using JPA

  • I have views in a SQL database with no obvious primary key (composite or otherwise)
  • I would like to access them through JPA

I've read that I should be able to treat views in JPA like I treat tables (using the @Table annotation etc.). However without a primary key I have to effectively make a composite key out of EVERY COLUMN (in fact, this in what Hibernate's reverse-engineering tool seems to do by default).

However if I do this there are undesirable side effects. E.g.

  • Having to write all you code pointing to the primary key's attributes rather than the views:

    myViewObject.getPrimaryKey().getFirstName()

  • Not being able to use the "findBy..." methods on the spring Repository (since that attribute is part of the view's "identifier" and not actually one of it's attributes).

My question is: How do I map views in such a was as I can easily access their attributes using JPA?

Note: I'm quite happy to be told I'm using completely the wrong approach. This seems like such a common problem there's bound to be a better solution.

like image 388
Andy N Avatar asked Jul 08 '15 12:07

Andy N


1 Answers

You can add a UUID column to every row of the Views so then you can use the UUID column as an @Id.

like image 60
Vlad Mihalcea Avatar answered Sep 20 '22 12:09

Vlad Mihalcea