Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Convert on @Id field

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?

like image 650
johncol Avatar asked May 19 '17 11:05

johncol


2 Answers

@Id and @Convert could not be used together. Using @IdClass can fix this problem. You just need to move @Convert to the @IdClass.

@Entity
@IdClass(PK.class)
public class YourClass {
  @Id
  private Long id;
  ...
}


public class PK implements Serializable {
  @Column(name = "MY_ID_FIELD")
  @Convert(converter = IdConverter.class)
  private Long id;
}
like image 124
RJ.Hwang Avatar answered Sep 24 '22 14:09

RJ.Hwang


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;
}
like image 38
Ravelle Kelley Avatar answered Sep 26 '22 14:09

Ravelle Kelley