You could use a custom type in your entity with JPA 2.1 @Convert
, so JPA makes the conversion for you (I've tested it with Spring Data JPA also, and it worked transparently!), see:
Entity:
@Entity
class SomeEntity {
@Column(name = "my_id_column_name")
@Convert(converter = MyIDConverter.class)
private ID itsID;
}
Converter:
public class MyIDConverter implements AttributeConverter<ID, String> {
@Override
public String convertToDatabaseColumn(ItStaticDataKey javaKey) {
// your implementation here
}
@Override
public ItStaticDataKey convertToEntityAttribute(final String databaseKey) {
// your implementation here
}
}
Notes:
- Make sure you're using a JPA-2.1-compatible Spring Data JPA version. (I'm sure that Spring Data JPA 1.7.0 (and above) are (or at least should) be compatible).
- Unfortunately, it won't work if that field should also be annotated with
@Id
. - If you use EclipseLink, you have to define converter in persistence.xml, or it doesn't pick it up. https://bugs.eclipse.org/bugs/show_bug.cgi?id=412454.
- With JPA on Spring, package containing converters have to appear in property
packageToScan
onEntityManagerFactoryBean
.