我正在尝试创建Java EE Web应用程序,但是从数据库获取单个结果时遇到问题。获取结果列表不是问题。
public UserCredentialsDTO findByUsernameAndPassword(String username, String password) {
EntityManager em = getEntityManager();
TypedQuery<UserCredentialsDTO> q = em.createNamedQuery("UserCredentialsDTO.findByUsernameAndPassword", UserCredentialsDTO.class);
//Query q = em.createNamedQuery("UserCredentialsDTO.findByUsernameAndPassword", UserCredentialsDTO.class);
q.setParameter("un", username);
q.setParameter("pw", password);
UserCredentialsDTO r = null;
try{
r = q.getSingleResult(); //This line is a problem
//r = (UserCredentialsDTO)q.getSingleResult();
} catch(javax.persistence.NoResultException e) {
}
return r;
}
同时使用Query和TypedQuery引发 java.lang.ClassCastException
java.lang.ClassCastException: wipb.jee.clientdemo.model.UserCredentialsDTO cannot be cast to wipb.jee.clientdemo.model.UserCredentialsDTO
编辑
UserCredentialsDTO:
@NamedQueries(
{@NamedQuery(name = "UserCredentialsDTO.findByUsernameAndPassword", query = "select uc from UserCredentialsDTO uc where uc.username=:un and uc.password=:pw")}
)
@Entity
@Table(name="USERCREDENTIALS", schema="APP")
public class UserCredentialsDTO implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@OneToMany(mappedBy = "userCredentials", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<UserGroupDTO> userGroups = new LinkedList<>();
//getters and setters
public void add(UserGroupDTO userGroup) {
userGroup.setUserCredentials(this);
this.userGroups.add(userGroup);
}
public List<UserGroupDTO> getUserGroups() {
return userGroups;
}
}