Reputation: 89
I am having some issues modeling a foreign key the way I like it in hibernate 4.1.9
I basically have the following code:
@Entity
@XmlRootElement
@Table(name="User")
public class UserVO
{
private String email;
@Id
@Column(name="email", unique=true, nullable=false)
@XmlElement
public String getEmail()
{
return this.email;
}
}
and this:
@Entity
@XmlRootElement
@Table(name="Authentification")
public class AuthentificationVO
{
private String email;
private UserVO user;
@Id
@Column(name="email", unique=true, nullable=false)
@XmlElement
public String getEmail()
{
return this.email;
}
@OneToOne(cascade = CascadeType.ALL)
@ForeignKey(name="user_fk")
public UserVO getUser()
{
return this.user;
}
}
The point of it all, is to have a column named email in both tables, which should also serve as a primary key for both the User and Authentification tables. For some reason, when I run this, Hibernate insists on adding a column to the Authentification table called user_email, but I want it to use the already existing column named email.
I tried looking around for a solution for this and I have tried using mappedBy annotation to get it right, along with JoinColumn, but nothing seems to do the trick.
Upvotes: 3
Views: 11067
Reputation: 89
What actually did the trick in the end was adding the following annotation:
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="email")
@MapsId
I removed the ForeignKey annotation, since it was disregarded when creating the table. The only effect is the naming of the constraint, which is now autogenerated by hibernate and I can live with that.
Upvotes: 2
Reputation: 10833
For a one to one you would need to specify @JoinColumn(name="user_fk")
for the mapping.
The @ForeignKey
annotation is just there to override the name of the foreign key generated by hibernate, not to tell to hibernate wich column to use (which is the role of the @JoinColumn
)
[Edit after comments]
Actually, as you are mapping on the primary key you should use the @MapsId
annotation to tell hibernate you are mapping to the Id of the OneToOne
associated entity.
Your mapping should then become :
@OneToOne(CascadeType.ALL)
@ForeignKey(name="email")
@MapsId
Upvotes: 1