IllegalArgumentException:为TypedQuery [model.User]指定的类型与查询返回类型[类model.User]不兼容

时间:2015-03-18 06:52:44

标签: java mysql hibernate jpa playframework

在为Generic类型创建TypedQuery时,我遇到了这种间歇性错误。我的方法如下:

    public List<T> findByEmail(Class type, String email_id){
        String query = "SELECT t FROM " + type.getSimpleName() + " t WHERE t.email =:"+email_id;
        TypedQuery<T> typedQuery =em.createQuery(query, type);
        return (List<T>) typedQuery.getResultList();            
   }

如果我重新启动服务器,则错误不再出现并且正确获取结果。

play.api.Application$$anon$1: Execution exception[[IllegalArgumentException: Type specified for TypedQuery [model.User] is incompatible with query return type [class model.User]]]
            at play.api.Application$class.handleError(Application.scala:296) ~[play_2.11-2.3.7.jar:2.3.7]
            at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.11-2.3.7.jar:2.3.7]
            at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun
    $applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.7.jar:
    2.3.7]
            at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun
    $applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.7.jar:2.3.7]
            at scala.Option.map(Option.scala:145) [scala-library-2.11.1.jar:na]
    Caused by: java.lang.IllegalArgumentException: Type specified for TypedQuery [model.User] is incompatible with query return type [class model.User]
            at org.hibernate.jpa.spi.AbstractEntityManagerImpl.resultClassChecking(AbstractEntityManagerImpl.java:387) ~[hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
            at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractE
    ntityManagerImpl.java:344) ~[hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final
    ]
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.
    0_25]
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:62) ~[na:1.8.0_25]
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:43) ~[na:1.8.0_25]

1 个答案:

答案 0 :(得分:-1)

问题是

TypedQuery<T> typedQuery =em.createQuery(query.toString(), type);

这里var类型是一个Class Object而不是User类,你需要做类似的事情。

TypedQuery<T> typedQuery =em.createQuery(query.toString(), Class.forName(type.getSimpleName()));

这将返回一个Class,TypedQuery将成为运行时的TypedQuery