Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

JPA Entity as JSF 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);
    }

    // ...
}

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);
    }

    // ...
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

E.g.

@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;
    }

}

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>

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...