@Convert on @Id field

Viewed 6410

I'm trying to

@Id
@Column(name = "MY_ID_FIELD")
@Convert(converter = IdConverter.class)
private Long id;

IdConverter is:

@Converter
public class IdConverter implements AttributeConverter<Long, BigDecimal> {

    @Override
    public BigDecimal convertToDatabaseColumn(Long attribute) {
        return BigDecimal.valueOf(attribute);
    }

    @Override
    public Long convertToEntityAttribute(BigDecimal dbData) {
        return dbData.longValue();
    }
}

The converter will map BigDecimal, the attribute field type Hibernate expects given that in the sql server database the id column type is numeric, to Long.

I'm using Spring Data Jpa and my repository is using Long as I would expect to

@Repository
public interface CityRepository extends JpaRepository<City, Long> { }

Do you have any idea of why it is not working?

3 Answers

In case anyone else runs into the same problem I did, you have to have the @Column annotation on the @IdClass in addition to @Converter for it to work (instead of relying on the naming strategy).

// doesn't work
public class PK implements Serializable {
  @Convert(converter = IdConverter.class)
  private Long id;
}
// works
public class PK implements Serializable {
  @Column(name = "ID")
  @Convert(converter = IdConverter.class)
  private Long id;
}

With EclipseLink 2.7.6 I've got the same problem.
My solution is:

Entity class:


    @Entity(name = "xxx")
    public class xxx implements Serializable {
      @EmbeddedId
      private XxxPk pk;
      ...
    }

ID class:


    @Embeddable
    public class XxxPk implements Serializable {
      @Column(name = "A_TYPE")
      @Convert(converter = ATypeAttributeConverter.class)
      private AType aTypeAttribute;
      ...
    }

Converter:


    import javax.persistence.AttributeConverter;
    import javax.persistence.Converter;
        
    @Converter
    public class ATypeAttributeConverter implements AttributeConverter<AType , String> {
        
      @Override
      public String convertToDatabaseColumn(AType agrType) { ... }
        
      @Override
      public AType convertToEntityAttribute(String code) { ... }
    }

Enumeration:


    public enum AType {
      E1, E2, ...;
      ...
    }

I've checked it also with EclipseLink-Converter (org.eclipse.persistence.annotations.Converter), but without success.

Related