ClassCastException 与 Hibernate ManyToMany 连接查询

ClassCastException with Hibernate ManyToMany Join Query

我有两个实体,奖励和用户,它们相关 manytomany 如下:

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

而用户:

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>();
}

我正在尝试使用以下查询从 FAVOURITE table 检索特定 user_idreward_id 的条目:

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

问题是当我 运行 这个查询并将查询结果等同于类型 Reward 时,我得到以下异常:

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.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.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.run(ServerRuntime.java:326)
    at org.glassfish.jersey.internal.Errors.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors.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)

此查询的休眠查询日志如下:

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=?

我想不出错误。有人可以帮忙吗?

编辑:我执行查询的部分是:

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;
        }
}

[Ljava.lang.Object 表示您的查询正在返回 array 个对象,而您正试图将其转换为一个对象。

更新: 由于您在没有 SELECT 子句的情况下进行查询并且还加入了 User、Hibernate returns RewardUser 对象,这就是为什么您得到 Object[].我可以想到两个解决方案。

  1. 您可以在 SELECT 子句中提及您想要获得的对象,例如 select r from Reward r join r.favouriteUsers u where u.userId = ? and r.rewardId = ?
  2. 或者,您可以在查询中使用 fetch,例如 from Reward r join fetch r.favouriteUsers u where u.userId = ? and r.rewardId = ?