9

JPA 2.1 introduced type converters. I have found examples of converters based on a single entity attribute.

Is it possible to create a type converter based on multiple entity attributes?
Are there some examples?

cassiomolin
  • 124,154
  • 35
  • 280
  • 359

2 Answers2

6

JPA 2.2 doesn't support this feature.

If you are using Hibernate, then you can simply use a Hibernate CompositeUserType.

Hibernate gives you the flexibility of mapping one or more SQL types to specific Domain Model subtypes (e.g. Currency, Money).

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • 1
    Thanks! I am developing an application which uses multiple persistence units. Entities from one persistence unit have relationships with entities from other persistence unit. My idea behind the converter was make this integration easier. Instead of use a basic attribute, I would use an entity from the other persistence unit and make the converter load the entity for me. I don't know if it works, but I would try. And the entity I would load within the converter has a composite key. So, I would need converters that support many database columns. – cassiomolin Aug 07 '14 at 11:54
  • The solution I found was create basic attributes and load my entity later (and store a reference for it in an attribute annotated with @Transient). Is there another way to do that? – cassiomolin Aug 07 '14 at 12:24
  • 1
    I wouldn't do that. If you have multiple persistence units then you can merge the results in the service layer in a domain object that aggregates data from both persistence units' entities. This is the job of the business layer, while persisting data is what Hibernate is all about. – Vlad Mihalcea Aug 07 '14 at 12:46
  • 1
    This answer from 2014 seems to be still relevant. Upstream issue: https://github.com/eclipse-ee4j/jpa-api/issues/105 – Avindra Goolcharan Apr 27 '20 at 17:51
  • @VladMihalcea but if you handle merging of the results in a Service layer, then the relationship would be limited only to a particular Service (in the vast majority of idiomatic setups). The question is seeking to establish relationships at the Entity layer, which should enable more broad usage of the relationship in your codebase. – Avindra Goolcharan Apr 27 '20 at 19:29
2

DataNucleus JPA has specific support for mapping an attribute to multiple columns, but that is not part of the JPA spec (i.e vendor extension).

There is no ability to map multiple entity attributes to one column (or to many columns).

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29