I have a simple form that intend to update a list of items in a cart. The form works pretty well, I display an input text for each item in the cart. But if I change an item text and then save, it fails with an hibernate error : PersistenceException occured : org.hibernate.PersistentObjectException: detached entity passed to persist: 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();
}
I think it s a common use case, however I m not sure to do it the right way.