Openjpa级联持久化将外键设置为null

时间:2013-04-17 09:53:15

标签: jpa null foreign-keys cascade persist

我有2个实体:路由主机主机具有引用路由' PK的FK字段route_id,也称为route_id。 我创建了对象路由并将 Hosts 对象添加到它的hostsCollection中。然后我坚持路由对象。两个主键都正确生成,新的路由记录正常,但主机记录在route_id字段中为NULL。我做错了什么?

Routes.java:

@Entity
public class Routes implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ROUTE_ID")
    private long routeId;

    @Column(name="MSG_QUEUE_NAME")
    private String msgQueueName;

    @Column(name="RECEIPT_QUEUE_NAME")
    private String receiptQueueName;

    @Column(name="QM_NAME")
    private String qmName;

    @OneToMany(mappedBy="routeId", cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    private Set<Hosts> hostsCollection;

    private static final long serialVersionUID = 1L;

    public Routes(String mqMgrName, String msgQName, String receiptQName, Set<Hosts> newHosts)
    {
        this.qmName = mqMgrName;
        this.msgQueueName = msgQName;
        this.receiptQueueName = receiptQName;
        this.hostsCollection = newHosts;
    }
    ...
}

Hosts.java:

@Entity
public class Hosts implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="HOST_ID")
    private long hostId;

    @Column(name="HOST_NAME")
    private String hostName;

    @Column(name="KEEP_MSG")
    private String keepMsg;

    @Column(name="SEND_RCPT")
    private String sendRcpt;

    @ManyToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="ROUTE_ID", referencedColumnName="ROUTE_ID")
    private Routes routeId;

    @OneToMany(mappedBy="hostId")
    private Set<Users> usersCollection;

    public Hosts(String hostName, String keepMsg, String sendRcpt)
    {
        this.hostName = hostName;
        this.keepMsg = keepMsg;
        this.sendRcpt = sendRcpt;
    }
    ...
}

创建对象:

public String createNewHost()
{
    Set<Hosts> newHosts = new HashSet<Hosts>();
    Hosts newHost = new Hosts(this.hostName, this.keepMsg, this.sendRcpt);
    newHosts.add(newHost);
    Routes newRoute = new Routes(this.mqMgrName, this.msgQName, this.receiptQName, newHosts);
    dataBean.setCurrentRoute(newRoute);
    return "ok";
}

持久对象:

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setCurrentRoute(Routes currentRoute) {
    em.persist(currentRoute);
    em.flush();
}

1 个答案:

答案 0 :(得分:0)

在Routes.hosts上你有mappedBy =“routeId”,这意味着,拥有关系的一方是Host。

因此,除非您在Host上设置关系,否则它将不会保留。