Search code examples
javapostgresqlhibernatemany-to-manynamed-query

ClassCastException with Hibernate ManyToMany Join Query


I have two entities, Reward and User, that are related manytomany as below:

public class Reward {
    @Id
    @Column(name="reward_id")
    private long rewardId;
    @ManyToMany(mappedBy="favourite")
    @LazyCollection(LazyCollectionOption.FALSE)
    private Collection<User> favouriteUsers;
}

And the User:

public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    @Column(name="user_id")
    private long userId;
    @ManyToMany
    @JoinTable(name="FAVOURITE", joinColumns=@JoinColumn(name="user_id"), inverseJoinColumns=@JoinColumn(name="favourite_id"))
    @LazyCollection(LazyCollectionOption.FALSE)
    private Collection<Reward> favourite = new ArrayList<Reward>();
}

I'm trying to retrieve an entry from FAVOURITE table for a specific user_id and reward_id using the below query:

@NamedQuery(name="Favourite.byUserAndReward", query="from Reward r join r.favouriteUsers u where u.userId = ? and r.rewardId = ?")

The problem is when i run this query and equate the result of the query to type Reward, I get the following exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.xxxxxxx.model.Reward
    at com.xxxxxxx.sevice.RewardService.addFavourite(RewardService.java:26)
    at com.xxxxxxx.resources.RewardResource.addFavourite(RewardResource.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

The hibernate query log for this query is below:

Hibernate: select favouriteu0_.favourite_id as favourit2_3_0_, favouriteu0_.user_id as user_id1_3_0_, user1_.user_id as user_id1_2_1_ from FAVOURITE favouriteu0_ inner join USER user1_ on favouriteu0_.user_id=user1_.user_id where favouriteu0_.favourite_id=?

I can't figure out the mistake. Can someone please help?

EDIT: Part where I'm executing the query is:

public Reward addFavourite(long userId, Reward favouriteReward) {
        Object<Reward> rewardObject = new ObjectImpl<Reward>();
        long favouriteId = favouriteReward.getRewardId();
        // Check if favourited before. 
        // Below is the line that throws the exception.
        Reward checkReward = rewardObject.getObjectByNamedQueryLongLong("Favourite.byUserAndReward", userId, favouriteId)
        if (checkReward != null) {
            return favouriteReward;
        }
}

Solution

  • [Ljava.lang.Object means your query is returning array of objects and you are trying to cast it to an object.

    UPDATE: Since you are querying without SELECT clause and also joining User, Hibernate returns both the Reward and User objects, that's why you are getting Object[]. I can think of two options to solve.

    1. You can mention the object that you want to get in the SELECT clause like select r from Reward r join r.favouriteUsers u where u.userId = ? and r.rewardId = ?
    2. Or, you can use fetch in your query like from Reward r join fetch r.favouriteUsers u where u.userId = ? and r.rewardId = ?