Hibernate子表保存空外键而不是自动增加父主键

时间:2015-08-03 17:28:40

标签: java mysql spring hibernate

我正在尝试同时保存到两个父表和子表。它确实保存了父行和子行,但问题是子表不包含子表中外键列中父表的主键(Auto Increment)。而不是子表中的外键列显示为null

这是模型 01.Feed Order类(父类)

@Entity
public class FeedOrder {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String date;
    private double total;
    private double discount;


    @OneToMany(mappedBy="feedOrder",cascade = CascadeType.PERSIST)
    private List<FeedOrderDetail> feedOrderDetail;

    @ManyToOne
    private Supplier supplier;
    //With Getters and Setters
}

02.Feed Order Details类(Child Class)

@Entity
public class FeedOrderDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private double unitPrice;
    private long quantity;

    @ManyToOne
    @JoinColumn(name="feed_id")
    private Feed feed;


    @ManyToOne
    @JoinColumn(name="order_id")
    private FeedOrder feedOrder;
    //With Getters and Setters
}

我也使用Spring MVC。

这是Repository类Code。

@Repository("feedOrderRepository")
public class FeedOrderRepositoryImp implements FeedOrderRepository {

    @PersistenceContext
    private EntityManager em;

    public FeedOrder save(FeedOrder feedOrder) {

        em.persist(feedOrder);
        em.flush();

        return null;
    }

}

更新

AddFeedOrder.jsp

<html>
<body>
<form:form commandName="feedOrder">

    <table>
        <tr>
            <td>Date</td>
            <td><form:input path="date" /></td>
        </tr>
        <tr>
            <td>Discount</td>
            <td><form:input path="discount" /></td>
        </tr>
        <tr>
            <td>Total</td>
            <td><form:input path="total" /></td>
        </tr>
        <tr>
            <td>Supplier</td>
            <td><form:input path="supplier.id" /></td>
        </tr>
    </table>
    <table id="mytable">
        <tr>
            <td>Feed ID</td>
            <td>Unit Price</td>
            <td>Quantity</td>
        </tr>
        <tr>
            <td><form:input path="feedOrderDetail[0].feed.id" /></td>
            <td><form:input path="feedOrderDetail[0].unitPrice" /></td>
            <td><form:input path="feedOrderDetail[0].quantity" /></td>
        </tr>

    </table>
    <INPUT type="button" value="Add More" onclick="addRow('mytable')" />
    <tr>
        <td><input type="submit" value="Save Feed Order"></td>
    </tr>

</form:form>

</body>
</html>

0 个答案:

没有答案