我刚刚开始使用 EJB。我想使用 JTA 从数据库中接收一些数据。我的实体:
@Entity
@Table(name = "User")
@NamedQuery(name = "User.findByAddressName",
query = "select u from User u where u.userAddress.addressName = :addressName")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long userID;
@Column(name = "userFirstName", length = 45)
private String userFirstName;
@Column(name = "userLastName", length = 45)
private String userLastName;
@Column(name = "userBirthDate")
private Date userBirthDate;
@Column(name = "userPhone")
private String userPhone;
@Column(name = "userPassword")
private String userPassword;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "addressUser")
private Email userAddress;
public User() {
}
public User(String userFirstName, String userLastName, Date userBirthDate, String userPhone, String userPassword) {
this.userFirstName = userFirstName;
this.userLastName = userLastName;
this.userBirthDate = userBirthDate;
this.userPhone = userPhone;
this.userPassword = userPassword;
}
}
我的道:
@Stateless
public class UserBean {
@PersistenceContext(unitName = "server")
private EntityManager em;
public User getUserByEmail(String email) {
TypedQuery<User> queryUser = em.createNamedQuery("User.findByAddressName",
User.class);
queryUser.setParameter("addressName", email);
return queryUser.getSingleResult();
}
}
我的服务:
@Stateless
public class LoginService {
@EJB
UserBean userBean;
public boolean loginUser(String userEmail, String userPass) {
User user = userBean.getUserByEmail(userEmail);
if (userPass.equals(user.getUserPassword())) {
return true;
} else return false;
}
}
我尝试接收数据:
boolean b = new LoginService().loginUser("user", "user1");
但是由@EJB 在LoginService 中注入的UserBean userBean 为null。
有很多简单的例子说明如何做这样的事情,我都做的一模一样,但是还是抛出NullPointerException,不知道为什么。