Hibernate Annotations:将int存储在varchar列中

Tom*_*sky 1 hibernate hibernate-annotations

我正在使用Hibernate Annotations.

在我的POJO中,我有一个年份字段,它是一个int.

我想将此值保存在我的数据库中的char(4)列中,并且hibernate来回转换类型.无论如何我可以轻松地做到这一点(我开始研究@Type注释,但是如果可能的话,我不想写自己的自定义类型)?

Ken*_*han 6

如果映射到DB的char(4)列的POJO字段是属性访问,则hibernate将调用其setter和getter来获取数据库和POJO之间的映射.因此,转换逻辑可以在该属性的setter和getter内实现.此外,intDate应标记为@Transient,告诉hibernate忽略映射此字段.

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;
    }

}
Run Code Online (Sandbox Code Playgroud)