I'm trying to map a OneToOne relationship as an entity identifier : in my schema a person can have 0 or 1 user account, thus user_accounts table's id is a foreign key referencing person's id.
Here's a sample of my class diagram :
Schema :
persons (id, ..., PK(id))
customers (id, ..., PK(id), FK(id) RF persons(id))
user_accounts(id, ..., PK(ID), FK(id) RF persons(id))
Here's a sample of UserAccount class :
Code:
@Entity
@Table(name = "user_accounts")
public class UserAccount extends core.business.model.mapping.Entity implements Serializable {
@Id
@OneToOne(targetEntity = Person.class, cascade = CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
private RegisteredUser user;
@Column(name = "email_address")
private String emailAddress;
@Column
private String hash;
@OneToOne(mappedBy = "userAccount",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private Token token;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserAccount that = (UserAccount) o;
return user.equals(that.user);
}
@Override
public int hashCode() {
return user.hashCode();
}
UserAccount() {
}
}
After a userAccount is returned from DAO, its user is null, which cannot be possible according to my model's constraints.
Here's the sql query generated by hibernate :
Quote:
select useraccoun0_.id as id4_25_, useraccoun0_.updated_at as updated_1_25_, useraccoun0_.email_address as email_ad2_25_, useraccoun0_.hash as hash3_25_, useraccoun0_1_.token_id as token_id0_24_ from user_accounts useraccoun0_ left outer join tokens__user_accounts useraccoun0_1_ on useraccoun0_.id=useraccoun0_1_.user_account_id where useraccoun0_.email_address='xxx@xxx.com' and useraccoun0_.hash='e13d212084f7d594e4c540474c0981d99dfe581a'
There is no join on persons table while it is expected to fetch it.
If I move RegistredUser into an @Embeddable class and embed it as an @EmbeddedId, the relationship is properly fetched, but it's quite "ugly" to proceed like so and Hibernate specs say at
the end of 2.2.3.1 section :
Quote:
Finally, you can ask Hibernate to copy the identifier from another associated entity. In the Hibernate jargon, it is known as a foreign generator but the JPA mapping reads better and is encouraged