tags:

views:

344

answers:

1

Hi, I'd like to achieve the following schema:

Table A:
a_id
(other columns)


Table B:
b_id
(other columns)


Table C:
c_id
(other columns)


Table D:
a_id_fk
b_id_fk
c_id_fk

I would like to know how to create entity D. All the keys a_id_fk, b_id_fk and c_id_fk in Table D form a composite primary key.

Thanks

+1  A: 

Hi,

It models a ternary association. In order to use it you need a map. JPA 1.0 does not support Map so if you want to use you need Hibernate because its Map suppport. It is something like

@Entity
public class A {

    @ManyToMany
    @org.hibernate.annotations.MapKeyManyToMany(
        joinColumns=@JoinColumn(name="B_ID")
    )
    @JoinTable(
        name="D",
        joinColumns=@JoinColumn(name="A_ID"),
        inverseJoinColumns=@JoinColumn(name="C_ID")
    )
    private Map<B, C> bAndC = new HashMap<B, C>();

}

Notice each key is a B and each value is a C entity. In practice, it binds A and C through a B entity.

@Entity
public class B {

    @Id
    private Integer id;

}

@Entity
public class C {

    @Id
    private Integer id;  

}

Or if you do not want a Map you can model a entity ABC according to

public class AbC {

    @ManyToOne
    @JoinColumn(name="A_ID", insertable=false, updateable=false)
    private A a;

    @ManyToOne
    @JoinColumn(name="B_ID", insertable=false, updateable=false)
    private B b;

    @ManyToOne
    @JoinColumn(name="C_ID", insertable=false, updateable=false)
    private C c;

    @EmbeddedId
    private A_b_C_i_D id;

    @Embeddable
    public static class A_b_C_i_D implements Serializable {

        @Column(name="A_ID", updateable=false)
        private Integer a_i_d;

        @Column(name="B_ID", updateable=false)
        private Integer b_i_d;

        @Column(name="C_ID", updateable=false)
        private Integer c_i_d;

        // getter's and setter's

        public boolean equals(Object o) {
            if(o == null)
                return false;

            if(!(o instanceof A_b_C_i_D))
                return false;

            A_b_C_i_D other = (A_b_C_i_D) o;
            if(!(getA_i_d().equals(other.getA_i_d()))
                return false;

            if(!(getB_i_d().equals(other.getB_i_d()))
                return false;

            if(!(getC_i_d().equals(other.getC_i_d()))
                return false;

            return true;
        }

        public int hashcode() {
            // hashcode implementation
        }

    }

}

regards,

Arthur Ronald F D Garcia
Thanks. Very descriptive and helpful
soontobeared
Good question. You are welcome
Arthur Ronald F D Garcia