Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two foreign keys as primary key

How would I implement the following tables using hibernate annotations?

enter image description here

Current code is: (stripped for brevity)

User

@Entity
@Table(name = "user")
public class User implements java.io.Serializable {
    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }
}

SocialNetwork

@Entity
@Table(name = "social_network")
public class SocialNetwork implements java.io.Serializable {
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
}

SocialProfile

@Entity
@Table(name = "social_profile")
public class SocialProfile implements java.io.Serializable {
    @Id
    @ManyToOne
    @JoinColumn(name="user_id")
    public User getUser() {
        return user;
    }

    @Id
    @ManyToOne
    @JoinColumn(name="social_network_id")
    public SocialNetwork getSocialNetwork() {
        return socialNetwork;
    }
}

Obviously my code is not working correctly right now. Can anyone shed some light onto this?

like image 770
prettyvoid Avatar asked Sep 22 '15 09:09

prettyvoid


1 Answers

you need an embeddable SocialProfileId like this :

@Embeddable
public class SocialProfileId implements Serializable {
    @Column(name = "user_id")
    private long userId;
    @Column(name = "social_network_id")
    private long socialNetworkId;
}

then, your SocialProfile entity will look like this :

@Entity
@Table(name = "social_profile")
public class SocialProfile implements java.io.Serializable {

    @EmbeddedId
    private SocialProfileId id;

    @ManyToOne
    @JoinColumn(name="user_id")
    public User getUser() {
        return user;
    }

    @ManyToOne
    @JoinColumn(name="social_network_id")
    public SocialNetwork getSocialNetwork() {
        return socialNetwork;
    }
}

EDIT sorry, i have mixed annotations on fields and methods on my answer ... never do that ! ;-)

like image 173
Pras Avatar answered Sep 28 '22 09:09

Pras