JPA实体为JSF Bean? [英] JPA Entity as JSF Bean?
问题描述
使用Entities作为JSF Backing Bean有意义吗?
Does it make sense to use Entities as JSF Backing Beans?
@Entity
@ManagedBean
@ViewScoped
public class User {
private String firstname;
private String lastname;
@EJB
private UserService service;
public void submit() {
service.create(this);
}
// ...
}
还是将它们分开保存并在最后将数据从支持bean传输到实体更好?
Or is it better to keep them separately and transfer the data from the backing bean to the entity at the end?
@ManagedBean
@ViewScoped
public class UserBean {
private String firstname;
private String lastname;
@EJB
private UserService service;
public void submit() {
User user = new User();
user.setFirstname(firstname);
user.setLastname(lastname);
service.create(user);
}
// ...
}
推荐答案
您可以这样做.从技术上讲这是可能的.但这在功能上没有任何意义.您基本上是在将模型与控制器紧密耦合.通常,JPA实体(模型)是JSF受管bean(控制器)的属性.这样可以使代码保持 DRY .您不想在所有地方都复制相同的属性,更不用说对这些属性的注释了,例如bean验证约束.
You could do so. It's technically possible. But it does (design)functionally not make any sense. You're basically tight-coupling the model with the controller. Usually the JPA entity (model) is a property of a JSF managed bean (controller). This keeps the code DRY. You don't want to duplicate the same properties over all place, let alone annotations on those such as bean validation constraints.
例如
@ManagedBean
@ViewScoped
public class Register {
private User user;
@EJB
private UserService service;
@PostConstruct
public void init() {
user = new User();
}
public void submit() {
service.create(user);
}
public User getUser() {
return user;
}
}
具有此Facelets页面(视图):
with this Facelets page (view):
<h:form>
<h:inputText value="#{register.user.email}" />
<h:inputSecret value="#{register.user.password}" />
<h:inputText value="#{register.user.firstname}" />
<h:inputText value="#{register.user.lastname}" />
...
<h:commandButton value="Register" action="#{register.submit}" />
</h:form>
另请参见:
- JSF MVC框架中的MVC是什么组件?
- JSF控制器,服务和DAO
- JSF中MVC的矛盾解释
- JSF 2重用了在JPA实体?
- 为什么不应由JSF管理实体bean框架?
- What components are MVC in JSF MVC framework?
- JSF Controller, Service and DAO
- Contradictory explanations of MVC in JSF
- JSF 2 reusing the validation defined in the JPA entities?
- why shouldn't entity bean be managed by JSF framework?
See also:
这篇关于JPA实体为JSF Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!