为什么简单的选择查询返回 List<Mymodel>但加入查询返回 List<Object>在 jpa [英] why simple select query returns List&lt;Mymodel&gt; but join query return List&lt;Object&gt; in jpa

查看:20
本文介绍了为什么简单的选择查询返回 List<Mymodel>但加入查询返回 List<Object>在 jpa的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 jpa 的 play 框架.我有一个带有 2 个函数的模型 Jobads to findall() findByLocation()

I am using play framework with jpa. I have a model Jobads with 2 functions to findall() findByLocation()

我的模特

  public class Jobads {

        @Id
        @Column(name = "id", nullable = false)
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;


        private String title;

        @ManyToOne
        private Jobindistry industry;


        @ManyToMany
        @JoinTable(
                name = "jobads_city",
                joinColumns = {@JoinColumn(name = "jobads_id", referencedColumnName = "id")},
                inverseJoinColumns = {@JoinColumn(name = "city_id", referencedColumnName = "id")})
        private List<City> city;
    }

findall()

 public static List<Jobads> findall() {
            @SuppressWarnings("unchecked")
            List<Jobads> el = JPA.em().createQuery("from Jobads order by id").getResultList();
            return el;
        }

findByLocation()

public static List<Jobads> findByLocation(String location) {
  List<Jobads> jadList = JPA.em().createQuery("FROM Jobads j join j.city c WHERE  c.name LIKE :location  ").setParameter("location", "%" + location + "%").getResultList();

return jadList;

}

我在控制台中打印两个函数输出 findall() 工作正常但 findByLocation() 给了我一个异常 [ClassCastException: [Ljava.lang.Object;不能转换为模型.Jobads]

I am printing both the function output in my console findall() works fine but findByLocation() gives me an exception [ClassCastException: [Ljava.lang.Object; cannot be cast to models.Jobads]

为什么这个问题只出现在 findByLocation() 中,这个问题的解决方法是什么??

Why this problem in occuring only in findByLocation() and what is the solution of this problem??

谢谢

推荐答案

发生这种情况是因为这就是没有 select 子句的 HQL 查询的工作方式.请注意,这些不是有效的 JPQL 查询.JPQL 强制使用 select 子句,使用 select 子句将允许您指定希望查询返回的内容:

It's happening because that's how HQL queries without a select clause work. Note that these are not valid JPQL queries. JPQL makes the select clause mandatory, and using a select clause would allow you to specify what you want the query to return:

select j from Jobads j join j.city c WHERE c.name LIKE :location

这篇关于为什么简单的选择查询返回 List<Mymodel>但加入查询返回 List<Object>在 jpa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆