views:

340

answers:

1

Hi

Can someone please advise on how to define & map (using annotations) custom types in Hibernate?

Eg, given:

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

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

Rather than having Point persisted as an object, I'd like to see Line persisted like:

startPointX , startPointY , endPointX , endPointY

What's the approriate way to do this?

Regards

Marty

+2  A: 

Custom types may not be the best way to handle this, since Point is a multi-value object. Instead, you can use @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;
}

It gets tricky when it comes to column mappings,since you need to override them to stop the two points from clashing.

skaffman