为什么简单的select查询返回List< Mymodel>但是加入查询返回列表< Object>在jpa [英] why simple select query returns List<Mymodel> but join query return List<Object> in jpa
问题描述
我的模型
public class Jobads {
@Id
@Column(name =id,nullable = false)
@GeneratedValue (strategy = GenerationType.AUTO)
private Long id;
private String title;
@ManyToOne
私人工作行业;
@ManyToMany
@JoinTable(
name =jobads_city,
joinColumns = {@JoinColumn(name =jobads_id,referencedColumnName = id)},
inverseJoinColumns = {@JoinColumn(name =city_id,referencedColumnName =id)})
private List< City>市;
}
findall()
public static List< Jobads> findall(){
@SuppressWarnings(unchecked)
列表< Jobads> el = JPA.em()。createQuery(from Jobads order by id)。getResultList();
return el;
}
findByLocation()
public static List< Jobads> findByLocation(String location){
列表< 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;为什么这个问题只出现在findByLocation()中,这个问题的解决方法是什么?
>谢谢
正在发生,因为这是HQL查询没有select子句的工作原理。请注意,这些不是有效的JPQL查询。 JPQL使select子句成为强制性,并且使用select子句将允许您指定要查询返回的内容:
select j从Jobads j加入j.city c WHERE c.name LIKE:location
I am using play framework with jpa. I have a model Jobads with 2 functions to findall() findByLocation()
My Model
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;
}
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]
Why this problem in occuring only in findByLocation() and what is the solution of this problem??
Thanks
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
这篇关于为什么简单的select查询返回List< Mymodel>但是加入查询返回列表< Object>在jpa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!