Hibernate fails to load JPA 2.1 Converter when loaded with spring-boot and spring-data-jpa

前端 未结 2 1274
说谎
说谎 2020-12-30 03:42

I have a custom converter for UUID to transfer it to a string instead a binary:

package de.kaiserpfalzEdv.commons.jee.db;
import javax.persistence.AttributeC         


        
相关标签:
2条回答
  • 2020-12-30 04:24

    Another option is to embed the conversion logic in alternative getters/setters, like so:

    public class SecurityTicket implements Serializable
    {
    ...
    private UUID id;
    
    @Transient
    public UUID getUUID()
    {
        return id;
    }
    
    @Id @NotNull
    @Column(name = "id_", length=50, nullable = false, updatable = false, unique = true)
    public String getID()
    {
        return id.toString();
    }
    
    public void setUUID( UUID id )
    {
        this.id = id;
    }
    
    public void setID( String id )
    {
        this.id = UUID.fromString( id );
    }
    
    ...
    

    The @Transient annotation will tell JPA to ignore this getter so it doesn't think there's a separate UUID property. It's inelegant, but it worked for me using JPA on classes with a UUID as PK. You do run the risk of other code setting bad values via the setId( String ) method, but it seems the only workaround. It may be possible for this method to be protected/private?

    While normal Java code would be able to distinguish to setters with the same name based on different argument types, JPA will complain if you don't name them differently.

    It's annoying that JPA doesn't support Converters on Ids or that it doesn't follow the JAXB convention of not requiring converters for classes with standard conversion methods (ie. toString/fromString, intValue/parseInt, etc. ).

    0 讨论(0)
  • 2020-12-30 04:41

    Andy Wilkinson gave the correct answer. Reading the spec helps in a lot of times.

    JPA 2.1 Converters are not applied to @Id annotated attributes.

    Thank you Andy.

    0 讨论(0)
提交回复
热议问题