Erdem Emekligil
Erdem Emekligil

Reputation: 184

Hibernate one to one with multiple columns

How can i bind two columns, using @OneToOne annotation?

Lets say I've 2 tables A and B.

Table A:

Table B:

In class A i want to write something like this:

@OneToOne(fetch = FetchType.EAGER, targetEntity = B.class)
@JoinColumn(name = "id1 and id2", referencedColumnName = "id1 and id2")
private B b;

Is it possible to do this using annotations?

Thanks.

Upvotes: 0

Views: 4843

Answers (1)

Rohit
Rohit

Reputation: 2152

What you need is composite keys.Use either @IdClass or @EmbeddedId

Example of @EmbeddedId something like this.

your composite key class:

@Embeddable
public class CompositePK implements Serializable {
    protected Integer id1;
    protected Integer id2;


    // equals, hashCode
}

Your Enity class :

@Entity
public class A{
    @EmbeddedId 
    private CompositePK compkey;

    @OneToOne(optional=true, mappedBy="A")
    private B b;

   ........
}

Upvotes: 1

Related Questions