我有兩個實體,如下列:Shound我避免使用mappedBy來保持我的應用程序穩定?
@Entity
public class Trip {
@OneToMany(mappedBy = "trip", fetch = FetchType.LAZY)
private Set<Job> jobs = new HashSet<Job>();
}
@Entity
public class Job {
@ManyToOne(fetch = FetchType.LAZY)
private Trip trip;
}
的問題是關係的mappedBy在不同情況下表現不同。下面是一個例子
EntityManager em1 = unit.createEntityManager();
EntityManager em2 = unit.createEntityManager();
// One EM starts transaction and stores a trip
em1.getTransaction().begin();
Trip trip = new Trip();
em1.persist(trip);
Long tripId = trip.getId();
assertThat(tripId).isPositive();
em1.getTransaction().commit();
// Then em2 starts different transaction
em2.getTransaction().begin();
// Looking up for the trip through clean em (cache is empty)
Trip em2Trip = em2.find(Trip.class, tripId);
Job job = new Job();
job.setTrip(em2Trip);
em2.persist(job);
// The em2Trip should not be updated
assertThat(em2Trip.getJobs()).hasSize(1);
em2.getTransaction().commit();
em1.getTransaction().begin();
Trip em1Trip = em1.find(Trip.class, tripId);
// fails here
assertThat(em1Trip.getJobs()).hasSize(1);
em1.getTransaction().commit();
上面的代碼表明,如果一個實體在實體管理器的緩存已經加載,對於關係的mappedBy吸氣劑返回無效結果。
我有一個證明它不能在JBoss下工作。以下代碼的行爲有所不同,具體取決於正在使用哪個實體管理器。結果是不可預測的。
Trip trip = em.find(Trip.class, tripId);
if (trip.getJobs().size() == 0) ...
這是否意味着mappedBy會在引入和使用後自動生成應用程序錯誤?
P.S.我不想濫用冬眠。我只想知道是否有人遇到了這樣的問題,他們是如何應對的?
請編輯您的問題,並儘量保持客觀。沒有人喜歡讀咆哮。 – 2009-08-14 13:31:38
現在好點了嗎? – artemb 2009-08-14 14:04:59