bidrectional foregin key one to one

This commit is contained in:
eugenp 2013-05-18 18:03:52 +03:00
parent fbb5402bf2
commit cb1c8cb3e2
3 changed files with 15 additions and 8 deletions

View File

@ -3,11 +3,9 @@ package org.baeldung.spring.persistence.model;
import java.io.Serializable; import java.io.Serializable;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity @Entity
public class Child implements Serializable { public class Child implements Serializable {
@ -16,8 +14,7 @@ public class Child implements Serializable {
@GeneratedValue @GeneratedValue
private long id; private long id;
@OneToOne(fetch = FetchType.LAZY) @OneToOne(mappedBy = "child")
@PrimaryKeyJoinColumn
private Parent parent; private Parent parent;
public Child() { public Child() {
@ -34,7 +31,6 @@ public class Child implements Serializable {
this.id = id; this.id = id;
} }
@OneToOne(mappedBy = "child")
public Parent getParent() { public Parent getParent() {
return parent; return parent;
} }

View File

@ -16,6 +16,8 @@ public class Parent implements Serializable {
@GeneratedValue @GeneratedValue
private long id; private long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "child_fk")
private Child child; private Child child;
public Parent() { public Parent() {
@ -38,8 +40,6 @@ public class Parent implements Serializable {
this.id = id; this.id = id;
} }
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "child_fk")
public Child getChild() { public Child getChild() {
return child; return child;
} }

View File

@ -28,7 +28,7 @@ public class ParentServicePersistenceIntegrationTest {
} }
@Test @Test
public final void whenEntityIsCreated_thenNoExceptions() { public final void whenOneToOneEntitiesAreCreated_thenNoExceptions() {
final Child childEntity = new Child(); final Child childEntity = new Child();
childService.create(childEntity); childService.create(childEntity);
@ -42,4 +42,15 @@ public class ParentServicePersistenceIntegrationTest {
System.out.println("Parent - child = " + service.findOne(parentEntity.getId()).getChild()); System.out.println("Parent - child = " + service.findOne(parentEntity.getId()).getChild());
} }
@Test
public final void whenChildIsDeleted_thenDataException() {
final Child childEntity = new Child();
childService.create(childEntity);
final Parent parentEntity = new Parent(childEntity);
service.create(parentEntity);
childService.delete(childEntity);
}
} }