Hibernate自定义类型定义

时间:2009-07-28 16:27:14

标签: java hibernate persistence

有人可以建议如何定义&在Hibernate中映射(使用注释)自定义类型?

例如,给定:

@Entity
public class Line {
    private Point startPoint;
    private Point endPoint;
}

public class Point
{
    private double x;
    private double y;
}

我不想将Point作为对象持久化,而是希望看到Line像:

一样

startPointX,startPointY,endPointX,endPointY

执行此操作的合适方式是什么?

此致

玛蒂

1 个答案:

答案 0 :(得分:2)

自定义类型可能不是处理此问题的最佳方法,因为Point是一个多值对象。相反,您可以使用@Embeddable

@Entity
public class Line {

    @Embedded 
    @AttributeOverrides( {
        @AttributeOverride(name="x", column = @Column(name="startPointX") ),
        @AttributeOverride(name="y", column = @Column(name="startPointY") )
    } )
    private Point startPoint;

    @Embedded 
    @AttributeOverrides( {
        @AttributeOverride(name="x", column = @Column(name="endPointX") ),
        @AttributeOverride(name="y", column = @Column(name="endPointY") )
    } )
    private Point endPoint;
}

@Embeddable
public class Point
{
    private double x;
    private double y;
}

当涉及列映射时,它变得棘手,因为你需要override them to stop the two points from clashing