12

配置

  • EcliplseLink 2.3.2
  • JPA 2.0
  • 实体是从 netbeans 的 db 模式自动创建的,带有来自数据库的实体类...向导。
  • 控制器类是使用来自实体类的 JPA 控制器类的 netbeans 自动创建的...向导

问题的简短版本

在经典场景中,两个表具有一对多关系。我创建父实体,然后创建子实体,并将子实体附加到父实体的集合中。当我创建(控制器方法)父实体时,我希望子实体被创建并与父实体相关联。为什么不发生?

长版

家长班

@Entity
@XmlRootElement
public class Device implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Integer id;
    @Column(unique=true)
    private String name;
    @Temporal(TemporalType.TIMESTAMP)
    private Date updated;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "deviceId")
    private Collection<NetworkInterface> networkInterfaceCollection;

    public Device() {
    }

    public Device(String name) {
        this.name = name;
        updated = new Date();
    }

    // setters and getters...

    @XmlTransient
    public Collection<NetworkInterface> getNetworkInterfaceCollection() {
        return networkInterfaceCollection;
    }

    public void setNetworkInterfaceCollection(Collection<NetworkInterface> networkInterfaceCollection) {
        this.networkInterfaceCollection = networkInterfaceCollection;
    }

    public void addNetworkInterface(NetworkInterface net) {
        this.networkInterfaceCollection.add(net);
    }

    public void removeNetworkInterface(NetworkInterface net) {
        this.networkInterfaceCollection.remove(net);
    }
    // other methods
}

儿童班

@Entity
@Table(name = "NETWORK_INTERFACE")
@XmlRootElement
public class NetworkInterface implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Integer id;
    private String name;
    @Temporal(TemporalType.TIMESTAMP)
    private Date updated;
    @JoinColumn(name = "DEVICE_ID", referencedColumnName = "ID")
    @ManyToOne(optional = false)
    private Device deviceId;

    public NetworkInterface() {
    }

    public NetworkInterface(String name) {
        this.name = name;
        this.updated = new Date();
    }

    // setter and getter methods...

    public Device getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(Device deviceId) {
        this.deviceId = deviceId;
    }
}

主班

public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("wifi-dbPU");
        DeviceJpaController deviceController = new DeviceJpaController(emf);
        NetworkInterfaceJpaController netController = new NetworkInterfaceJpaController(emf);

        Device device = new Device("laptop");
        NetworkInterface net = new NetworkInterface("eth0");

        device.getNetworkInterfaceCollection().add(net);
        deviceController.create(device);
    }
}

此类在行中抛出 NullPointerException:device.getNetworkInterfaceCollection().add(net);

系统知道有一个新实体device,并且它的集合中有一个元素net。我希望它写入device数据库,获取设备的 ID,将其附加到net数据库中并将其写入数据库。

而不是这个,我发现这些是我必须做的步骤:

deviceController.create(device);
net.setDeviceId(device);
device.getNetworkInterfaceCollection().add(net);
netController.create(net);

当父类知道它是孩子并且应该为我创建它时,为什么我必须创建孩子?

DeviceJpaController 中的 create 方法(对不起,字段中的长名称,它们是自动生成的)。

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

public void create(Device device) {
    if (device.getNetworkInterfaceCollection() == null) {
        device.setNetworkInterfaceCollection(new ArrayList<NetworkInterface>());
    }
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Collection<NetworkInterface> attachedNetworkInterfaceCollection = new ArrayList<NetworkInterface>();
        for (NetworkInterface networkInterfaceCollectionNetworkInterfaceToAttach : device.getNetworkInterfaceCollection()) {
            networkInterfaceCollectionNetworkInterfaceToAttach = em.getReference(networkInterfaceCollectionNetworkInterfaceToAttach.getClass(), networkInterfaceCollectionNetworkInterfaceToAttach.getId());
            attachedNetworkInterfaceCollection.add(networkInterfaceCollectionNetworkInterfaceToAttach);
        }
        device.setNetworkInterfaceCollection(attachedNetworkInterfaceCollection);
        em.persist(device);
        for (NetworkInterface networkInterfaceCollectionNetworkInterface : device.getNetworkInterfaceCollection()) {
            Device oldDeviceIdOfNetworkInterfaceCollectionNetworkInterface = networkInterfaceCollectionNetworkInterface.getDeviceId();
            networkInterfaceCollectionNetworkInterface.setDeviceId(device);
            networkInterfaceCollectionNetworkInterface = em.merge(networkInterfaceCollectionNetworkInterface);
            if (oldDeviceIdOfNetworkInterfaceCollectionNetworkInterface != null) {
                oldDeviceIdOfNetworkInterfaceCollectionNetworkInterface.getNetworkInterfaceCollection().remove(networkInterfaceCollectionNetworkInterface);
                oldDeviceIdOfNetworkInterfaceCollectionNetworkInterface = em.merge(oldDeviceIdOfNetworkInterfaceCollectionNetworkInterface);
            }
        }
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
4

5 回答 5

22

我终于明白了坚持一对多实体背后的逻辑。过程是:

  1. 创建父类
  2. 坚持下去
  3. 创建子类
  4. 将孩子与父母联系起来
  5. Persist child(父集合更新)

带代码:

public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("wifi-dbPU");
        DeviceJpaController deviceController = new DeviceJpaController(emf);
        NetworkInterfaceJpaController netController = new NetworkInterfaceJpaController(emf);

        Device device = new Device("laptop");                 // 1
        deviceController.create(device);                      // 2

        NetworkInterface net = new NetworkInterface("eth0");  // 3
        net.setDeviceId(device.getId());                      // 4
        netController.create(net);                            // 5 
        // The parent collection is updated by the above create     
    }
}

现在,我可以找到一个设备(例如带有 id),我可以让它的所有孩子使用

Collection<NetworkInterface> netCollection = device.getNetworkInterfaceCollection()

在我在问题中发布的设备实体类中,不需要方法addNetworkInterfaceremoveNetwokrInterface.

于 2013-01-04T08:01:56.530 回答
4

@Dima K 的说法是正确的。当你这样做时:

    Device device = new Device("laptop");
    NetworkInterface net = new NetworkInterface("eth0");

    device.getNetworkInterfaceCollection().add(net);
    deviceController.create(device);

设备中的集合尚未初始化,因此在尝试添加时会得到 NPE。在您的Device班级中,在声明您的 时Collection,您还可以对其进行初始化:

private Collection<NetworkInterface> networkInterfaceCollection = new CollectionType<>();

至于坚持,你的假设是正确的,但我认为执行是错误的。创建设备时,立即使用 JPA 使其持久化(在需要的地方进行事务管理)。

Device device = new Device("laptop");
getEntityManager().persist(device);

对 NetworkInterface 执行相同操作:

NetworkInterface net = new NetworkInterface("eth0");
getEntityManager().persist(net);

现在,由于您的两个实体都是持久的,您可以将一个添加到另一个。

device.getNetworkInterfaceCollection().add(net);

JPA 应该负责其余的工作,而您不必调用任何其他持久性。

于 2013-01-02T22:37:06.317 回答
2

这是集合数据成员的已知行为。最简单的解决方案是修改您的集合吸气剂以延迟创建集合。

@XmlTransient
public Collection<NetworkInterface> getNetworkInterfaceCollection() {
    if (networkInterfaceCollection == null) {
        networkInterfaceCollection = new Some_Collection_Type<NetworkInterface>();
    }
    return networkInterfaceCollection;
}

此外,请记住仅通过 getter 方法引用此数据成员。

于 2013-01-02T22:18:25.897 回答
0

此异常意味着您正在尝试定位尚未持久化的实体(可能通过 em.getReference())。您不能在仍然没有 PK 的实体上使用 em.getReference() 或 em.find()。

于 2013-01-02T22:42:14.727 回答
-1

为了启用 @OneToMany 关系的保存功能,例如

@OneToMany(mappedBy="myTable", cascade=CascadeType.ALL) 
private List<item> items;

然后你必须告诉你的 @ManyToOne 关系,它可以像这样更新 myTable 可更新 = true

@ManyToOne @JoinColumn(name="fk_myTable", nullable = false, updatable = true, insertable = true)
于 2015-07-19T09:08:24.887 回答