JPA实体为JSF Bean? [英] JPA Entity as JSF Bean?

查看:106
本文介绍了JPA实体为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>

另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆