是否有将JPA实体字段直接绑定到JSF组件的最佳实践?

时间:2015-07-08 15:09:04

标签: jsf jpa

我发现自己在这里来回走动。对于简单的POJO,将简单字段绑定到组件通常非常简单:

<h:outputText value="#{myPage.user.name}"/>
<h:outputText value="#{myPage.user.birthday}">
    <f: ....

但是,当涉及到管理集合或对象时,我发现自己想要一个&#34;包装器&#34;可以更容易管理的对象。例如,在POJO中管理集合需要(至少在JSF 2.1中)将其包装在DataModel或List中。因此,包装对象将具有getter / setter / actionListeners以帮助促进管理。

既然JSF 2.2已经出现了,你可以将Collections实际映射到JSF组件......所以JSF似乎越来越容易直接映射到实体。

我想保持一致。人们通常会尽可能地映射到实体,然后在其页面中使用包装器方法来管理异常吗?或者,您是否将整个对象用于组件绑定?

1 个答案:

答案 0 :(得分:0)

One size does not fit all scenarios, directly binding entity beans to pages is possible with several frameworks, but is not necessarily a good idea. A simple project can benefit from the immediacy of direct binding, but it is easy to run into situations that dictate exceptions to this rule.

The reason behind this is that UI is not necessarily an exact representation of the backing entities (i.e., the info you enter into input fields does not fit exactly into entity fields and require transformation). Suppose a simple example, you could need to put the value of three different input fields (like day, month and year of a date) into a single field in the entity with java.util.Date type. This is a case in which UI does not match the backing data model. Constraining either one, or both, to adapt to the constraints of the other is not a good solution (in the example, you either change the three input fields into a single one, or worse yet change the entity bean to have three columns to store the date).

This type of problems is usually solved introducing a layer that isolates between the data model and the view, in the form of DTOs or similar data-carrying objects that handle differences in mappings (again from the example, you have a DTO that provides the three fields to store the deconstructed date and synthesizes a java.util.Date object by combining the three values.

In JSF many of these concerns can be addressed with the use of converters, but these solutions can be difficult to maintain (you change a page and you find yourself having to change the converter). Also some use cases are too complex to handle in converters (for example collections).

In a nutshell, the answer is "it depends". Simpler applications with simple interactions and UI requirements can safely use direct binding. More complex applications usually require more separation between the tiers and additional functionality that direct binding cannot address.