5

Imagine I have one common functionality: series and number (string and integer) of some document. My object (insurance policy) contains information about series and number of different documents, so I would like to group this series and number into one java object and let hibernate store two fields on each object in the same table.

See the example:

    class Polis {
        private DocInfo kaskoNumber;
        private DocInfo osagoNumber;
        private DocInfo tsNumber;
    }
    class DocInfo {
        private String series;
        private Integer number;
    }
    table:
    polis(kaskoSeries varchar2, 
          kaskoNumber numeric, 
          osagoSeries varchar2, 
          osagoNumber numeric..... )

Something like this. What I really want to do - to get rid of duplication of fields in Polis object and incapsulate series and number fields in DocInfo object. This is ok for java, but as for Hibernate the only way I know - is to create ManyToOne relation and move this information to the other table (doc_info). But I need to keep all the information in one table!

Thanks.

axtavt
  • 239,438
  • 41
  • 511
  • 482
bitec
  • 606
  • 1
  • 11
  • 23

2 Answers2

10

Use @Embeddable and @AttributeOverrides:

@Entity
class Polis {
    @AttributeOverrides( {
        @AttributeOverride(name="series", column = @Column(name="kaskoSeries") ),
        @AttributeOverride(name="number", column = @Column(name="kaskoNumber") )
    })
    private DocInfo kaskoNumber;

    @AttributeOverrides( {
        @AttributeOverride(name="series", column = @Column(name="osagoSeries") ),
        @AttributeOverride(name="number", column = @Column(name="osagoNumber") )
    })
    private DocInfo osagoNumber;
    ...
}

@Embeddable
class DocInfo {
    private String series;
    private Integer number;
}

See also:

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Great help, thanks a lot! Annotations are a bit monsterous, but java class became more readable and convenient. – bitec Feb 20 '11 at 15:16
0

You want a Hibernate "component"--which in JPA is called an "embeddable" object. The component/embeddable has the two fields, and your entity class just has one instance of the component/embeddable. The two columns live in the entity table along with the rest of the entity's fields.

Willis Blackburn
  • 8,068
  • 19
  • 36
  • I should mention, you can have multiple instances of the same component/embeddable in a single entity class, each mapping to different columns. I've done this many times myself. – Willis Blackburn Feb 20 '11 at 14:43