How would I implement the following tables using hibernate annotations?
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?
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 ! ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With