但是一時找不到放哪去!
還是來做個筆記!
實作一對多的例子!
一個帳號會對應到多個留言
先建立一個data_account.java(這個是父類別)
//省略import
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class data_account {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
private String encodedKey; //編碼的Key,自動產生
@Persistent
@Extension(vendorName="datanucleus" , key="gae.pk-id", value="true")
private Long id; //自動產生
@Persistent
private String account;
@Persistent
private Date date = new Date();
@Persistent(mappedBy = "da") //這裡名稱是對應到data_plurk裡面的data_account xx這個名稱
Listdata_plurks; //一對多關係的標註
//setter省略
//getter也省略
}
在建立一個data_plurk.java(這個是子類別)
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class data_plurk {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value ="true")
private String encodedKey; //編碼的Key,//自動產生
@Persistent
@Extension(vendorName="datanucleus", key="gae.pk-id", value="true")
private Long id;//自動產生
@Persistent
private String content;
@Persistent
@Extension(vendorName="datanucleus", key="gae.parent-pk", value="true")
private Key plurkKey; //父類別的設置
@Persistent
private data_account da; //一對一關係的標註
//setter省略
//getter也省略
接著就是做insert的操作了!
建立一個toInsert.java的servlet
public class toInsert extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
data_account da = new data_account();
da.setAccount("test");
da.setDate(new Date());
pm.makePersistent(da);
Key daKey = KeyFactory.stringToKey(da. getEncodedKey());
data_plurk dp1 = new data_plurk();
dp1.setConten("hi");
dp1.setEmployee (da);
dp1.setKey(daKey); //將data_account設為父類別
da.getPlurkSets().add(dp1); //保證data_account的一對多
pm.makePersistent(dp1);
data_plurk dp2 = new data_plurk();
dp2 .setConten("hi");
dp2 .setEmployee (da);
dp2 .setKey(daKey); //將data_account設為父類別
da.getPlurkSets().add(dp2 ); //保證data_account的一對多
pm.makePersistent(dp2 );
}catch(Exception e){
resp.getWriter().println(e.toString());
}finally {
pm.close();
}
}
}