我正在尝试用Netbean构建一个应用程序。我使用Eclipse IDE&JPA API。实体如下:
纳茨。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
}
城市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;
}
}
当我想添加新的NAT对时&城市,我用这个:
一些豆子。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);
}
}
服务内容如下:
通用资源。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中正确显示,但在会话结束时。由于外键未保存,因此会丢失关系。持久化完成后,NATs实体中的capId为空。所以我需要一个坚持&1合并以完成此操作。除了使用我评论的那句话,还有更好的解决方案吗?
非常感谢。