【问题标题】:update @OneToMany in Play framework在 Play 框架中更新 @OneToMany
【发布时间】:2011-11-23 19:35:51
【问题描述】:

我有一个简单的表单,打算更新购物车中的商品列表。 表单效果很好,我为每个项目显示一个输入文本 购物车。但是,如果我更改项目文本然后保存,它会失败并显示 休眠错误: 发生 PersistenceException : org.hibernate.PersistentObjectException:分离的实体传递给 坚持:models.Item

这是表格:

<section class="form">
    #{form @save()}
        <input type="hidden" name="cart.id" value="${cart?.id}">

        <p class="field">
            <label for="title">Title :</label>
            <input type="text" name="cart.title" value="${cart?.title}"
            maxlength="50" size="50"/>
            <span class="error">${errors.forKey('cart.title')}</span>
        </p>

        <div id="items">
            #{if cart && cart.items}
                            #{list items:cart.items, as:'item'}
                                    <input type="hidden" name="cart.items[${item_index}].id" value="${item?.id}">
                                    <input type="text"    name="cart.items[${item_index}].text" value="$
{item?.text}"/>
                        #{/list}
                    #{/if}
        </div>

        <p class="buttons">
            <a href="@{index()}">Cancel</a> <input type="submit" value="Save" id="savecart">
        </p>
    #{/form}
</section>

我的实体和控制者:

@Entity
public class Cart extends Model {
    @Required
    public String title;

    @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL)
    public List<Item> items;

    public Cart(String title) {
            this.title = title;
            this.items = new ArrayList<Item>();
    }
}


@Entity
public class Item extends Model {
    @Required
    public String text;

    @ManyToOne
    @Required
    public Cart cart;

    public Item(String text, Cart cart) {
            this.text = text;
            this.cart = cart;
    }

}

public static void save(Cart cart){
    validation.valid(cart);
            if (validation.hasErrors()) {
                    validation.keep();
                    formCart(cart.id);
            }
            cart.save();
            index();
} 

我认为这是一个常见的用例,但我不确定是否会这样做 正确的方法。

【问题讨论】:

    标签: jpa playframework one-to-many


    【解决方案1】:

    您必须在保存之前合并您的实体

    cart = cart.merge();
    cart.save();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多