根据此示例https://github.com/datanucleus/samples-jdo/blob/master/many_to_many_attributed/src/main/java/org/datanucleus/samples/jdo/many_many_attributed2/Main.java,我使用以下代码创建了CompanyProduct关系。
Company.java
@PersistenceCapable(identityType = IdentityType.APPLICATION, cacheable = "false", detachable = "true")
public class Company implements Serializable {
...
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
long id;
@Persistent
private String name = null;
@Persistent(defaultFetchGroup = "true", mappedBy = "company")
private Set<CompanyProduct> companyProduct = new HashSet<>();
...
}
Product.java
@PersistenceCapable(identityType = IdentityType.APPLICATION, cacheable = "false", detachable = "true")
public class Product implements Serializable {
...
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
long id;
@Persistent
private String name = null;
@Persistent(defaultFetchGroup = "true", mappedBy = "product")
private Set<CompanyProduct> companyProduct = new HashSet<>();
...
}
CompanyProduct.java
@PersistenceCapable(identityType = IdentityType.APPLICATION, cacheable = "false", detachable = "true")
public class CompanyProduct implements Serializable {
...
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
long id;
@Persistent
private String name = null;
@Persistent(defaultFetchGroup = "true")
private Company company;
@Persistent(defaultFetchGroup = "true")
private Product product;
...
}
Main.java
...
tx.begin();
CompanyProduct companyProduct = new CompanyProduct();
Company company = pm.getObjectById(Company.class, companyId);
Product product= pm.getObjectById(Product.class, productId);
companyProduct.setCompany(company);
companyProduct.setProduct(product);
company.addCompanyProduct(companyProduct);
product.addCompanyProduct(companyProduct);
pm.makePersistent(companyProduct);
tx.commit();
...
删除关系
tx.begin();
CompanyProduct comProd= pm.getObjectById(CompanyProduct.class, companyProduct.getId());
comProd.removeCompanyProduct(comProd);
comProd.removeCompanyProduct(comProd);
pm.makePersistent(comProd);
tx.commit();
从关联对象中删除关系对象,会在提交后自动删除关系对象。如果我想将它重新添加到相关对象,我无法再次访问它。 我在这里做错了什么?
答案 0 :(得分:-1)
我能够通过将依赖和依赖元素属性添加并设置为false来解决此自动删除问题。我按如下方式更新了我的代码;
Company.java
...
@Persistent(defaultFetchGroup = "true", mappedBy = "company", dependentElement = "false")
private Set<CompanyProduct> companyProduct = new HashSet<>();
...
Product.java
@Persistent(defaultFetchGroup = "true", mappedBy = "product", dependentElement = "false")
private Set<CompanyProduct> companyProduct = new HashSet<>();
CompanyProduct.java
...
@Persistent(defaultFetchGroup = "true", dependent = "false")
private Company company;
@Persistent(defaultFetchGroup = "true", dependent = "false")
private Product product;
...