我有一個簡單的設置與兩個對象,Event
和Task
作爲父子和鏈接和一些CRUD操作的默認JPA存儲庫。我做了一個測試,我在其中附加了2 Task
s到Event
,然後我嘗試對這些Task
s之一調用delete
操作,該操作失敗(沒有錯誤,也沒有刪除)。春季引導休眠:無法單獨刪除子對象
如果我運行相同的測試,但不將Task
添加到Event
,則操作成功。我下面的所有代碼,關於接下來我需要做什麼的想法?
@Entity
public class Event {
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "hibernate-uuid", strategy = "uuid2")
@Column(unique = true)
String id;
String subject;
@OneToMany(mappedBy="event", cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
@JsonIgnoreProperties({"event"})
List<Task> tasks;
}
@Entity
public class Task {
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "hibernate-uuid", strategy = "uuid2")
@Column(unique = true)
String id;
String subject;
@ManyToOne
@JsonIgnoreProperties({"tasks"})
Event event;
}
public interface TaskRepository extends JpaRepository<Task, String> {
public Task findById(String id);
}
而且測試:
@Test
public void testSequenceOfActionsOnEventWithSubtasks() {
// Save a new task
Task savedTask = given()
.body(
new TaskBuilder()
.subject("Previously saved task")
.build()
).contentType(ContentType.JSON)
.when().post(TASKS_RESOURCE).as(Task.class);
Task unsavedTask = new TaskBuilder()
.subject("Unsaved task")
.build();
// Save a new event with an unsaved and a saved task attached
Event savedEvent = given()
.body(
new EventBuilder()
.subject("Main event")
.addTask(savedTask)
.addTask(unsavedTask)
.build()
).contentType(ContentType.JSON)
.when().post(EVENTS_RESOURCE).as(Event.class);
// Make sure the event now contains two tasks with GUID's attached
List<Task> tasksForEvent = when().get(EVENT_RESOURCE, savedEvent.getId()).as(Event.class).getTasks();
assertEquals(2, tasksForEvent.size());
// Get all tasks, make sure firstTask is in there
when().get(TASKS_RESOURCE).then().body(SUBJECT_FIELD, hasItems(savedTask.getSubject()));
// Delete a task that was attached to the event
when().delete(TASK_RESOURCE, savedTask.getId()).then().statusCode(HttpStatus.SC_OK);
// Get all tasks, make sure firstTask is NOT in there
when().get(TASKS_RESOURCE).then().body(SUBJECT_FIELD, not(hasItems(savedTask.getSubject())));
// Check the event again
tasksForEvent = when().get(EVENT_RESOURCE, savedEvent.getId()).as(Event.class).getTasks();
assertEquals(1, tasksForEvent.size());
}
更新:如果我從@OneToMany
上的Event
類中刪除fetch = FetchType.EAGER
,它的工作原理。但仍然很高興知道爲什麼。以下是我的新課程Event
。
@Entity
public class Event {
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "hibernate-uuid", strategy = "uuid2")
@Column(unique = true)
String id;
String subject;
@OneToMany(mappedBy="event", cascade = { CascadeType.ALL })
@JsonIgnoreProperties({"event"})
List<Task> tasks;
}