Preface
I've got a classical Parent-Child problem. Here's the code:
When I'm trying to save a bean tree in one go:Code:@Entity public class Supply { @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH }, mappedBy = "supply") private List<SupplyItem> items = new ArrayList<SupplyItem>(); // Getters/Setters and id field } @Entity public class SupplyItem { @NotNull @ManyToOne private Supply supply; private Integer quantity; // Getters/Setters and id field }
Naturally I get ConstraintViolationException since I have validation configured and item.supply is null.Code:Supply supply = new Supply(); SupplyItem item = new SupplyItem(); supply.getItems().add(item); entityManager.persist(supply);
Hibernate in Action suggests the following approach:
ProblemCode:public class Supply { // Skipped public void addItem(SupplyItem item) { item.setSupply(this); items.add(item); } // Skipped } Supply supply = new Supply(); SupplyItem item = new SupplyItem(); supply.addItem(item); entityManager.persist(supply);
The problem is that I don't populate items by hand, thus I cannot use a helper addItem() method. Instead I get my supply object constructed via web binding. The items list is populated by means of list autogrowing facility.
So my view markup looks like this:
I know that I could iterate over all the supply items and set the back reference to supply, but that looks like a hack to me.HTML Code:<form:form modelAttribute="supply"> <!-- Other supply fields --> <form:input path="items[0].quantity" /> <form:input path="items[1].quantity" /> </form:form>
So I wonder is there any other way to make binder/expression parser/whatever to do that for me? Maybe I could provide the factory method for supply items creation somehow?
If that matters I use WebFlow, but I would like to know whether it is possible for MVC too.


? Maybe I could provide the factory method for supply items creation somehow?
Reply With Quote
.
