Datanucleus:超类型的双向1-N关系

时间:2017-09-15 12:40:54

标签: java database entity jdo datanucleus

我正在尝试在datanucleus中建模以下关系:

@PersistenceCapable
@Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
@Discriminator(strategy = DiscriminatorStrategy.CLASS_NAME)
public class Item {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.NATIVE)
    private Long id;
}

@PersistenceCapable
public class Address extends Item {

    @Persistent
    protected Item owner;
    ...
}

@PersistenceCapable
public class Customer extends Item {

    @Persistent(mappedBy = "owner")
    @Join
    protected List<Address> addresses;
}

@PersistenceCapable
public class PointOfSales extends Item {
    @Persistent(mappedBy = "owner")
    @Join
    protected List<Address> addresses;
}

PointOfServiceCustomer类都可以有多个Address关系。

另一个Address类型的owner字段应引用所属对象(CustomerPointOfService

这些是数据库表:

Database tables

这是代码[UPDATE]:

public class Main {
    public static void main(String args[]) {
        PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("Tutorial");

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();

        try {
            tx.begin();

            Address addr1 = new Address();
            addr1.setPostalCode("1210");
            Customer cust1 = new Customer();
            cust1.setFirstName("Test");
            // cust1.setAddresses(Arrays.asList(addr1));
            addr1.setOwner(cust1);

            Address addr2 = new Address();
            addr2.setPostalCode("3333");
            Customer cust2 = new Customer();
            cust2.setFirstName("sdgsdgs");
            // cust2.setAddresses(Arrays.asList(addr2));
            addr2.setOwner(cust2);

            pm.makePersistent(addr1);
            pm.makePersistent(addr2);

            pm.makePersistent(cust1);
            pm.makePersistent(cust2);

            addr2.setOwner(cust1);
            pm.makePersistent(addr2);

            PointOfSales pos = new PointOfSales();
            pos.setAddresses(Arrays.asList(addr2));

            // that's the place where the error occurs
            pm.makePersistent(pos);

            tx.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
    }
}

pm.makePersistent(pos)

时出错

这会导致错误:

  

javax.jdo.JDOUserException:Object“org.datanucleus.samples.jdo.tutorial.entities.PointOfSales@16fdec90”有一个集合“org.datanucleus.samples.jdo.tutorial.entities.PointOfSales.addresses”但是元素“ org.datanucleus.samples.jdo.tutorial.entities.Address@561868a0“将其所有者设置为”org.datanucleus.samples.jdo.tutorial.entities.Customer@740d2e78“。这是不一致的,需要纠正。

您是否知道如何以某种方式开展此项工作,我可以向客户添加地址,地址'所有者是与客户自动填充的。 反之亦然:设置所有者并自动添加到相应的客户

感谢您的帮助。

0 个答案:

没有答案