Skip to content
Advertisement

Does JPA support mapping to sql views?

I’m currently using Eclipselink, but I know now days most JPA implementations have been pretty standardized. Is there a native way to map a JPA entity to a view? I am not looking to insert/update, but the question is really how to handle the @Id annotation. Every entity in the JPA world must have an ID field, but many of the views I have created do not conform to this. Is there native support for this in the JPA or do I need to use hacks to get it to work? I’ve searched a lot and found very little information about doing this.

Advertisement

Answer

While using the @Id annotation with fields of directly supported types is not the only way to specify an entity’s identity (see @IdClass with multiple @Id annotations or @EmbeddedId with @Embedded), the JPA specification requires a primary key for each entity.

That said, you don’t need entities to use JPA with database views. As mapping to a view is no different from mapping to a table from an SQL perspective, you could still use native queries (createNativeQuery on EntityManager) to retrieve scalar values instead.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement