我创建了 JPA 实体 USER。然后 UserDao 作为接口,UserDaoBean 作为实现。
@Stateless
public class UserDaoBean implements UserDao {
@PersistenceContext
private EntityManager em;
private CriteriaBuilder qb;
@Override
public User getUserByUsername(String username) {
qb = em.getCriteriaBuilder();
CriteriaQuery<User> c = qb.createQuery(User.class);
Root<User> u = c.from(User.class);
Predicate condition = qb.equal(u.get("username"), username);
Logger.getLogger(UserDaoBean.class.getName()).log(Level.SEVERE, u.get("username").toString());
c.where(condition);
TypedQuery<User> q = em.createQuery(c);
List<User> results = q.getResultList();
if (results != null && !results.isEmpty()) {
return results.get(0);
}
return null;
}
当我创建例如。HomePage.java,对应HomePage.html和form,我可以用
@Inject
private UserDao userdao;
一切正常。但我创建了 UsernameValidator:
public class UsernameValidator implements IValidator<String>{
@Inject
private UserDao userDao;
@Override
public void validate(IValidatable<String> iv) {
String username = iv.getValue();
User user = userDao.getUserByUsername(username);
...
}
}
userDao 上有 NullPointerException。我不明白,注入是如何在页面中工作的,而不是在验证器中。