我試圖用Netbean構建一個應用程序。我使用Eclipse IDE & JPA API。該實體是這樣的:Ecplise JPA添加新的父對象
NATS.java
@Entity
@Table(name = "NATS")
Public Class NATS implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer code;
private String nName;
@Column(name = "cap_id") // for foreign key purpose
private Integer capId;
@OneToOne(cascade=CascadeType.PERSIST)
@PrimaryKeyJoinColumn(name = "cap_id")
private City capital;
public City getCapital(){
return this.capital;
}
public void setCapital (City newcapital){
this.capital = newcapital;
}
... some gets & sets methods
}
City.java
@Entity
public class City implements Serializable {
private static final long serialVersionUID = 1L;
private String cityName;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private Integer cityId;
public String getCityName() {
return cityName;
}
public void setCityName(String newcityName) {
this.cityName = newcityName;
}
public City(String ctname) {
this.cityName = ctname;
}
public Integer getcityId() {
return cityId;
}
public void setcityId(Integer ctId) {
this.cityId = ctId;
}
}
當我要添加新的對NATS &市,我用這個:
somebean.java
@Stateless
public class somebean {
@PersistenceContext(unitName = "TestLocal")
private EntityManager em;
public NATs insertNewCC(String capitalname, String countryname){
City newcapital = new City(capitalname);
NATS newcountry = new NATS();
newcountry.setNationName(countryname);
newcountry.setCapital(newcapital);
em.persist(newcountry); // both objects persisted well, with "capId" still null
return newcountry;
}
public void updateCapitalId(Nations country){
country.setCapitalId(country.getCapital().getcityId());
em.merge(country);
}
}
這裏是服務:
genericResource.java
@Path("generic")
public class GenericResource {
@Context
private UriInfo context;
@EJB
private somebean r;
@GET
@Path("/inscountry")
@Produces("application/json")
public List<NATS> insCountry(@QueryParam("countryname") String countryname, @QueryParam("capitalname") String capitalname){
NATS newcountry = r.insertNewCC(capitalname, countryname);
//r.updateCapitalId(newcountry); <-- i want to avoid using this line
List<NATS> result= r.getListNATS();
return result;
}
當我註釋行:r.updateCapitalId(newcountry); 我得到一對國家和首都城市的關係正確顯示在JSON中,但會議關閉時。它會損失關係,因爲外鍵沒有保存。持久化完成後,NAT實體中的capId爲空。所以我需要1個堅持& 1合併來完成這一點。除了使用我評論的那條線之外,還有更好的解決方案嗎? 謝謝。
你確定這是你的代碼..?它看起來像它甚至不會編譯和嵌套實體是一件非常糟糕的事情,難道你不能爲每個實體分開類嗎? –
它來自不同的.java文件。我實際上將每個實體寫入不同的文件。 –