Why does a simple select query return List <Mymodel> but attach a return List <Object> query in jpa

I am using play framework with jpa. I have a Jobads model with 2 functions for 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 typing as the output of a function in my console. findall () works fine, but findByLocation () is giving me an exception. [ClassCastException: [Ljava.lang.Object; cannot be applied to models. Jobads]

Why does this problem only occur in findByLocation () and what is the solution to this problem?

thank

+3
java exception model-view-controller jpa playframework


source to share


3 answers


This is because HQL queries without a select clause are working. Please note that these are invalid JPQL queries. JPQL makes the select clause mandatory, and using the select clause will allow you to specify that you want the query back:



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

      

+2


source to share


Think about what your second query is returning: you will have a table with two rows because of the operator join

. However, I don't know what the output type will be in this case, try using it getClass

to view.



+1


source to share


createQuery()

the method takes two parameters, a query and a query result type, so you can write a type safe query like this:

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

+1


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics