4

In jpa (>= 2.1) how can you create an AttributeConverter for an attribute annotated with @Id?

Unfortunately, it seems like Hibernate does not allow it in the following code: org.hibernate.cfg.annotations.SimpleValueBinder#applyAttributeConverter

if ( property.isAnnotationPresent( Id.class ) ) {
            LOG.debugf( "Skipping AttributeConverter checks for Id attribute [%s]", property.getName() );
            return;
}

Is there any way to circumvent this?

w.devilus
  • 53
  • 1
  • 4
  • Just out of curiosity, what are you using as the PK? – Kayaman Mar 21 '17 at 13:56
  • That's a shame, since other JPA providers do allow it, and can't see a good reason why not to allow it ... – Neil Stockton Mar 21 '17 at 14:12
  • You should file a ticket to have it changed https://hibernate.atlassian.net/browse/HHH. They probably had some internal design considerations for it when they made the restriction, but maybe they're not valid any more and it could be just legacy code. – coladict Mar 21 '17 at 15:29
  • Ok, I just found the answer for it. Seems like JPA specs does not allow it. See: https://hibernate.atlassian.net/browse/HHH-8820 https://hibernate.atlassian.net/browse/HHH-9172 https://hibernate.atlassian.net/browse/HHH-8809 Seems really stupid IMHO, but... Will look for an alternative. @Kayaman I am using my own Date type as primary key. I'd really appreciate if any one has a suggestion, thanks! – w.devilus Mar 21 '17 at 18:40
  • A date as a primary key, ouch. :) Have you considered a surrogate key? – Kayaman Mar 21 '17 at 18:44
  • @Kayaman Yeah, I agree with you. Unfortunately I have no say at the database design, nor is it changeable anymore. – w.devilus Mar 21 '17 at 19:19

2 Answers2

2

Just found a nice workaround as I had the same problem as Hibernate was serializing the object even with @Convert all the time, except... for those where I used it inside an @Embeddable

  @Embeddable
  public static class Key {
    @Column(name = "ID", nullable = false)
    @Convert(converter = MyObjectConverter.class)
    private MyObject id;
//getter/setter
  }

  @EmbeddedId
  private Key key;
  • 1
    The downside is that instead of doing `myEntity.id` you now need to do `myEntity.key.id`, both in JPQL queries and in actual Java property access. – Frans Feb 20 '20 at 14:37
0

I've found that you can use UUID as an id and then converter is allowed Persisting UUID in PostgreSQL using JPA It's strange you can't use any custom Converter

Marx
  • 804
  • 10
  • 23