I have legacy table in which one of its column's type is varchar but there is all numbers in it. I don't want to change datatype in table. I want to change the column data type in entity.
Before it was string now i changed it to Integer and crud operations are working fine. Is this fine doing or there is some other way of doing it? Sample code:
Before:
@Entity
public class TestEntity{
@Column(name = "Test")
private String test;
}
Now:
@Entity
public class TestEntity{
@Column(name = "Test")
private Integer test;
}
Create an AttributeConverter
which will be use for Database to entity type converstion
@Converter
public class IntegerToStringConverter implements AttributeConverter < Integer,
String > {
@Override
public String convertToDatabaseColumn(Integer value) {
return Integer.toString(number);
}
@Override
public Integer convertToEntityAttribute(String number) {
try {
return Integer.parseInt(number);
} catch (Exception e) {
throw new IllegalStateException("Invalid number: " + value);
}
}
}
And use it on your column
@Convert(converter = IntegerToStringConverter.class)
@Column(name = "Test")
private Integer Test;