0

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

路线.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;
    }
    ...
}

主机.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();
}
4

1 回答 1

0

在 Routes.hosts 上,您已映射过 =“routeId”,这意味着关系的拥有方是主机。

因此,除非您在 Host 上设置关系,否则它不会被持久化。

于 2013-04-24T15:19:37.123 回答