why simple select query returns List but

2019-02-24 10:34发布

问题:

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

回答1:

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


回答2:

Think about what is returned by your second query : you will have a table with two rows due to the join statement. However, I don't really know what will be the type of the output in this case, try using getClass on it to see.



回答3:

createQuery() method accepts two parameters, query and the type of the query result, thus you can write type safe query this way:

createQuery("FROM Jobads j join j.city c WHERE c.name LIKE :location", Jobads.class);