2

I have a table with three columns, "A", "B" and "C". Two of these columns (A and B) are the composite primary key for the table. I've written a Java class for this table and I'm using Hibernate to map the data in the class to the data in the table. I've created another class for the Embedded (i.e., composite) key.

The two classes look like this:

@Entity
@Table(name="SOME_TABLE", schema="SOME_SCHEMA")
public class Outer {
    private Key key;
    private String a;
    private String b;
    private String c;

    @EmbeddedId
    public Key getId() {
        return this.key;
    }

    // Also a setter for Key...

    @Column(name="A")
    public String getA() {
        return this.a;
    }

    public void setA(final String a) {
        this.a = a;
    }

    // Also setters and getters for B and C.
}

.

@Embeddable
public class Key {
    private String a;
    private String b;

    @Column(name="A")
    public String getA() {
        return this.a;
    }

    public void setA(final String a) {
        this.a = a;
    }

    // Also a getter & setter for B.
}

It seems like all the Hibernate documentation glosses over where, exactly, the getters and setters should go. Should both Outer and Key have setters for the values that make up the composite key? If I do have a setter in both places, does Hibernate do the right thing (i.e., set the value on Key) if I set the value for A on Outer? Should Outer.getA/B() and Outer.setA/B() defer to the Key class?

I think it's bad coding practice to have setters in two places for the same data. It's ambiguous at the very least. I'm hoping that Hibernate will set the values on the Key class for me, but I'd like to know for sure. Thanks!

-joe

1 Answer 1

1

I am not 100% sure with @EmbeddedId but I think it must be handled the same way as regular @Embedded properties, so I think the mapping should be like this:

@Entity
@Table(name="SOME_TABLE", schema="SOME_SCHEMA")
public class Outer {
    private Key key;
    // no fields a and b here
    private String c;

    @EmbeddedId
    public Key getId() {
        return this.key;
    }

    // Also a setter for Key...

    @Transient
    public String getA() {
        return this.key.getA();
    }

    public void setA(final String a) {
        this.key.setA(a);
    }

    @Transient
    public String getB() {
        return this.key.getB();
    }

    public void setB(final String b) {
        this.key.setB(b);
    }

    // Also setters and getters for C.
}
1
  • Thanks, tscho. I rarely use @Embedded, so I didn't jump to the connection there. I guess, to answer my original question, "delegate to the key" is the approach. Dec 8, 2011 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.