我有一对多拥有的关系。这是我的父类:
@XmlRootElement
@Entity
public class Strip {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private long id;
private String filename = "";
@OneToMany(mappedBy = "strip", cascade = CascadeType.ALL)
private List<Quote> quotes = new ArrayList<Quote>();
public long getId() {
return key.getId();
}
public void setId(long id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public List<Quote> getQuotes() {
return quotes;
}
public void setQuotes(List<Quote> quotes) {
this.quotes = quotes;
}
public Key getKey() {
return key;
}
}
和子班:
@XmlRootElement
@Entity
public class Quote {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private long id;
private String quote = "";
@ManyToOne
private Strip strip;
public long getId() {
return key.getId();
}
public void setId(long id) {
this.id = id;
}
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
@XmlTransient
public Strip getStrip() {
return strip;
}
public void setStrip(Strip strip) {
this.strip = strip;
}
}
还有一种在 Strip 中添加 Quote 的方法:
public JResponse<StripResult> putStripWithQuote(@PathParam("strip_id") long id, Quote quote) {
StripResult result = new StripResult();
EntityManager em = EMFService.get().createEntityManager();
Strip strip = null;
try {
em.getTransaction().begin();
strip = em.find(Strip.class, id);
if (strip == null) {
result.setCode("0");
result.setMessage("Strip is not found.");
} else {
strip.getQuotes().add(quote);
}
em.getTransaction().commit();
} catch (Exception e) {
result.setCode("0");
result.setMessage("Exception: " + e.getMessage());
} finally {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
result.setStrip(strip);
return JResponse.ok(result).build();
}
执行此方法后,我可以在 Datastore Viewer 中看到我已经更新了现有的 Strip 实体和新的 Quote 实体。
即使我查询所有报价一切正常,我也能看到所有报价。
Query q = em.createQuery("select from " + Quote.class.getName());
list = new ArrayList<Quote>(q.getResultList());
m我的问题:entityManager.find(Quote.class, "id of existing quote")
不返回任何东西。
我在这里做错了什么或错过了什么?持久性上下文有问题吗?