0
我已經編寫了一個服務方法importCategories()
,它從數據庫中檢索一個類別列表,並遞歸地填充屬性和父類別。我遇到的問題是新類別創建了兩次,,除了,當我使用@Transactional
註釋complete()
時。任何人都可以向我解釋爲什麼這是?在將其添加到父級之前,我將其保存起來,然後將子級集合上的父級保存爲CascadeType.ALL
。Spring Data JPA實體創建兩次
型號:
@Entity
public class Category implements Identifiable<Integer> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer key;
private String name;
@ManyToOne
private Category parent;
@OneToMany(mappedBy="parent", cascade = {CascadeType.ALL})
private List<Category> children = new ArrayList<Category>();
public void add(Category category) {
category.setParent(this);
children.add(category);
}
}
服務:
@Transactional
private void complete(Category category) {
// ... (getting category info such as "name" and "parent key" from web service)
category.setName(name);
category = categoryRepository.saveAndFlush(category);
if (category.getParent() == null) {
Category parentCategory = new Category();
parentCategory.setKey(parentKey);
List<Category> categories = categoryRepository.findByKey(parentKey);
if (categories.size() > 0) {
parentCategory = categories.get(0);
}
parentCategory.add(category);
parentCategory = categoryRepository.saveAndFlush(parentCategory);
if (parentCategory.getParent() == null) {
complete(parentCategory);
}
}
}
public void importCategories() {
List<Category> list = categoryRepository.findAll();
for (Category category : list) {
complete(category);
}
}