JPA プロジェクトに 2 つのエンティティがあります。
カテゴリと質問。したがって、各カテゴリには質問のリストがあり、各質問はカテゴリの一部になります (1 対多の関係)。両方のエンティティで set/add メソッドを使用して双方向の関係を管理します。
質問 :
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Qcategory")
private Category category;
public void setCategory(Category category) {
this.category = category;
if (category != null && !category.getQuestions().contains(this)) {
category.addQuestion(this);
}
}
カテゴリー :
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "category")
private List<Question> questions= new ArrayList<Question>();
public void addQuestion(Question question) {
this.questions.add(question);
if (question.getCategory() != this) {
question.setCategory(this);
}
}
最初にカテゴリを作成します。
Category category1 = new Category();
category1.setName = "exampleCategory";
これをリポジトリからデータベースに追加します(以下の質問 addOrUpdate と同様の方法で追加されます)
その後、質問を作成します
Question question1 = new Question();
質問のカテゴリをcategory1に設定しました
question.setCategory = category1;
この後、以下の addOrUpdate メソッドを呼び出して、質問をデータベースに永続化しようとします。その後、エラーが発生します:
....:javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: jpa.entities.Category
次のようなリポジトリメソッドを使用します。
@Override
public boolean addOrUpdate(Question question) {
EntityManagerFactory emf = JPARepositoryFactory
.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Question tempQuestion = null;
try {
if (question.getId() != null) {
tempQuestion = em.find(Question.class,
question.getId());
}
if (tempQuestion == null) {
em.persist(question);
} else {
tempQuestion .setCategory(question.getCategory());
... (other setters)
tempQuestion = em.merge(question);
}
} catch (Exception e) {
....logging... }
tx.commit();
em.close();
emf.close();
return true;
}
どんな提案でも大歓迎です。