简体   繁体   中英

Map Varchar column type to Integer in entity jpa

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;

You can resolve it via getter/setter for the field in the database and applying @Transient annotation to the integer property.

@Entity
public class TestEntity {
    @Column(name = "test") 
    private  String getTest() {
        return String.valueOf(this.intTest);
    }

    private void setTest(String test) {
        try {
            this.intTest = Integer.parseInt(test);
        } catch (NumberFormatException e) {
            this.intTest = 0;
        }
    }

    @Transient
    private int intTest;

    public int getIntTest() { return intTest; }

    public void setIntTest(int test) {
        this.intTest = intTest;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM