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

亡梦爱人 提交于 2019-11-30 11:29:48
klenkes74

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.

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. ).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!