我擁有一對多的擁有關係。這裏是我的父類:GAA上的JPA:查找不返回記錄,但數據存儲的記錄很少
@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;
}
}
而且有方法在帶鋼添加引用:
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();
}
執行這種方法,我可以在看後我已更新現有Strip實體和新報價實體的Datastore Viewer。
即使我查詢所有報價一切工作正常,我能夠看到所有報價。
Query q = em.createQuery("select from " + Quote.class.getName());
list = new ArrayList<Quote>(q.getResultList());
mMy問題:entityManager.find(Quote.class, "id of existing quote")
不會返回任何內容。
我在做什麼錯或在這裏失蹤?持久性上下文有問題嗎?
我的意思是在你的查詢報價對象,要查找的id是來自DB的'key'列,而不是'id'列。或者你需要將'@ Id'移到'long id;'行之上。 – JScoobyCed
如果我將@Id移動到長ID,我將出現以下錯誤:不支持的主鍵類型:長 – barmaleikin
作爲查找函數的第二個參數我使用key.getId()值,我使用json和客戶端向客戶端發送此ID回到服務器 – barmaleikin