Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

ejb 3.0 - java.lang.ClassCastException with the same class object

This piece of code irritates me, sometimes it working and some other times it doesn't !

The NamedQuery : (name = "User.findByLogin", query = "SELECT u FROM User u WHERE u.login = :login")

public User findByLogin(String login) {
        Query query = em.createNamedQuery("User.findByLogin");
        query.setParameter("login", login);
        try {
            return (User) query.getSingleResult();
        } catch (javax.persistence.NoResultException ex) {
            return null;
        }
    }

The error make me crazy !

Avertissement: EJB5184:A system exception occurred during an invocation on EJB UserFacade, method: public dz.admin.entity.User dz.admin.service.UserFacade.findByLogin(java.lang.String) Avertissement: javax.ejb.EJBException .... Caused by: java.lang.ClassCastException: dz.elit.admin.entity.User cannot be cast to dz.elit.admin.entity.User at dz.elit.admin.service.UserFacade.findByLogin(UserFacade.java:45)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I face same issue in my spring-boot application and waste my so much time to solve it.

Issue is generate because of classloaders.

Classloaders of Model class and Session class both are different.

System.out.println("ClassLoader : " + Employee.class.getClassLoader());
System.out.println(session.getClass().getClassLoader()); //Hibernate Session object

ClassLoader : org.springframework.boot.devtools.restart.classloader.RestartClassLoader@a3af3c
sun.misc.Launcher$AppClassLoader@1d16e93

I face this issue because of this dependency.

<dependency>
  <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

When i comment this then my code working fine, so i suggest you to please check your jars.

System.out.println("ClassLoader : " + Employee.class.getClassLoader());
System.out.println(session.getClass().getClassLoader()); //Hibernate Session object

ClassLoader : sun.misc.Launcher$AppClassLoader@1d16e93
sun.misc.Launcher$AppClassLoader@1d16e93

Hope this answer help you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...