1

我正在使用休眠注释。

在我的 POJO 中,我有一个 int 年份字段。

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

4

2 回答 2

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

}
于 2011-02-24T05:50:01.317 回答
1

我对 Hibernate 资源进行了快速搜索,但我认为没有一种类型可以用于此目的:

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

但我鼓励你实现自己的类型(也许是年份类型?),因为它并不像听起来那么困难 :-)

另一种解决方案,在你的 setter 中处理转换,也是一种选择,但如果没有大量的测试和性能测量,我不会这样做。

于 2011-02-24T06:11:14.570 回答