开发者

Hibernate Annotations: Store an int in a varchar column

开发者 https://www.devze.com 2023-02-13 06:00 出处:网络
I\'m using Hibernate Annotations. In my POJO I have a year field which is an int. I would like to persist this value in a char(4) column in my DB, and have hibernate convert the types back and forth

I'm using Hibernate Annotations.

In my POJO I have a year field which is an int.

I would like to persist this value in a char(4) column in my DB, and have hibernate convert the types back and forth. Is there anyway I can easily do this (I started to look into the @Type annotation, but don't want to have to write my own custom type开发者_如何学运维 if possible)?


If the POJO 's field that is mapped to DB 's char(4) column is access by property , hibernate will then call its setter and getter for the mapping between the database and the POJO . Thus , the conversion logic can be implemented inside the setter and getter of this property. Besides , intDate should be mark as @Transient to tell hibernate to ignore mapping this field.

public class TableABC {

    private int id;
    private int intDate;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column(length=4) 
    private  String getCharDate() {
        return String.valueOf(this.intDate);
    }

    private void setCharDate(String charDate) {
        try {
            this.intDate = Integer.parseInt(charDate);
        } catch (NumberFormatException e) {
            //Logic to handle when charDate cannot convert to integer 
            this.intDate = 0;
        }
    }

    @Transient
    public int getIntDate() {
        return intDate;
    }

    public void setIntDate(int intDate) {
        this.intDate = intDate;
    }

}


I did a quick search on Hibernate sources, and I don't think there's a type that you could use for that:

https://github.com/hibernate/hibernate-core/tree/master/hibernate-core/src/main/java/org/hibernate/type

But I'd encourage you to implement your own Type (maybe a Year type?), as it's not as difficult as it may sound :-)

The other solution, to handle the conversion in your setter, is also an option, but I wouldn't do it without a lot of testing and performance measurements.

0

精彩评论

暂无评论...
验证码 换一张
取 消