I would like to create two table USER and USERDETAIL to fulfill:
-
USERDETAIL have reference to USER table.
-
Operation on USER table do not need to aware of USERDEAIL table existence.
This should be one-to-one non bidirectional relationship.
The entity classes:
@Entity
@Table(name="USER")
public class User implements Serializable{
@Id
@Column(name="ID")
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
//...
}
@Entity
@Table(name="USERDETAIL")
public class UserDetail implements Serializable{
@Id
@Column(name="ID")
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign",
parameters = @Parameter(name = "property", value = "user"))
private String id;
@OneToOne(optional= false , targetEntity=User.class, cascade= CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
//@JoinColumn(name="foreign_id",referencedColumnName="ID")
@PrimaryKeyJoinColumn
private User user;
//...
}
This create two table correctly and the USERDETAIL have foreign key constraint that its primary key is refernece by USER’s id. However, the on Delete action is Restrict but not Cascade. I cannot delete a row of USER because of this.
I am using MySQL Sever 5.1. It does not seem like it does not support on delete action is cascade. Because I can manually delete the constraint and add a new constraint that set to on delete is cascade and work as I expected.
Finally, I have solved the problem.
First of all, I have follow http://www.mkyong.com/hibernate/hibernate-one-to-one-relationship-example-annotation/ to create oneToOne mapping entities.
However, when I start the Tomcat, it always throw
NullPointerExceptionon mapping. Therefore, I come up with my question entities and seem to work fine except the deletion.I finally realize it is just a bug that hibernate-anoatation cause. I then use 3.4.0.ga version and follow the link again. By replace
@GeneratedValue(strategy = IDENTITY)(I don’t know why using this, hibernate cannot create table) toit work as I expected.
Although there is no foreign-key constrain on the table, deleting owner (USER) table really can also delete the child (USERDETAIL) table correctly with hibernate handle.
I also do not need to worry about update owner table with no child field on it. The
mappedByside actually has no physical mapping defined as Khue Vu said. Hibernate is smart enough not to delete the relation.