我可以将实体注入受管Bean并直接持久化吗? [英] Can I Inject an Entity to a Managed Bean and directly persist?
本文介绍了我可以将实体注入受管Bean并直接持久化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我想要做的:
<!DOCTYPE html>
<html
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:head>
<title>Sign Up Page</title>
</h:head>
<h:body>
<div class="well" style="margin-top: 20px">
<h2>Please Sign Up</h2>
</div>
<h:form>
<h:outputLabel for="username">User name:</h:outputLabel>
<h:inputText id="username" value="#{signUpPage.user.username}" />
<h:outputLabel for="password">Password:</h:outputLabel>
<h:inputSecret id="password" value="#{signUpPage.user.password}" />
<h:outputLabel for="passwordAgain">Password Again:</h:outputLabel>
<h:inputSecret id="passwordAgain" value="#{signUpPage.passwordAgain}" />
<br />
<h:commandButton value="Submit" styleClass="btn btn-primary"
action="#{signUpPage.addUser}"/>
</h:form>
</h:body>
</html>
和托管bean:
@ManagedBean
@ViewScoped
public class SignUpPage {
@Inject
private User user;
@Inject
private UserDao userDao;
private String passwordAgain;
public String getPasswordAgain() {
return passwordAgain;
}
public void setPasswordAgain(String passwordAgain) {
this.passwordAgain = passwordAgain;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void addUser(){
userDao.persistUser(this.user);
}
}
实体:
@Stateless
@Entity
@Table(name = "user")
public class User {
private int id;
private String username;
private String password;
@Column(name = "id")
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
@Column(name = "username")
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
@Column(name = "password")
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
}
所以这行不通,因为用户解析为null.
So this does not work, because user resolves to be null.
反正有这样做吗?
我得到的异常是:
javax.servlet.ServletException: /signupPage.xhtml @34,82 value="#{signUpPage.user.username}": Target Unreachable, 'null' returned null
推荐答案
您需要自己创建一个空用户实体.通常,在使用JSF时,最好在懒惰的getter中创建和加载.只需更改吸气剂:
You need to create empty user entity by yourself. Generally when using JSF lazy creating and loading in getters is the best way. Just change the getter:
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
还请记住有关验证的信息.
Also remember about validation.
//编辑 您可能混合了注释,请阅读 https://stackoverflow.com/a/12012663/221951
//edit You've probably mixed annotations, read https://stackoverflow.com/a/12012663/221951
这篇关于我可以将实体注入受管Bean并直接持久化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文