使用JPA查询的java.lang.ClassCastException

时间:2018-06-19 13:36:45

标签: java jpa java-ee

我正在尝试创建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;
    }


}

1 个答案:

答案 0 :(得分:0)

这似乎是一个环境问题,在该环境中,JPA和应用程序的其余部分使用了不同的类加载器。

Refer to this thread