gpt4 book ai didi

jsf - JPA实体作为JSF Bean?

转载 作者:行者123 更新时间:2023-12-04 02:59:25 26 4
gpt4 key购买 nike

使用实体作为JSF支持Bean是否有意义?

@Entity
@ManagedBean
@ViewScoped
public class User {

private String firstname;
private String lastname;

@EJB
private UserService service;

public void submit() {
service.create(this);
}

// ...
}

还是将它们分开保存并在最后将数据从支持Bean传输到实体是更好的选择?
@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);
}

// ...
}

最佳答案

您可以这样做。从技术上讲这是可能的。但这在功能上没有任何意义。您基本上是在将模型与 Controller 紧密耦合。通常,JPA实体(模型)是JSF受管bean( Controller )的属性。这将保留代码DRY。您不想在所有地方都复制相同的属性,更不用说对这些属性的注释了,例如bean验证约束。

例如。

@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页面( 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>

也可以看看:
  • 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?
  • 关于jsf - JPA实体作为JSF Bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10301363/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com