hhrzc
hhrzc

Reputation: 2050

Hibernate query. Cast classes

Have hql query

List<Developer> developers = session.createQuery("from Developer d " +
              "left join ProjectDeveloper pd on pd.developer.id = d.id " +
              "where pd.project.id = " + project.getId()).getResultList();

it work and get a list of the objects, but not a Developer.

Actually, the object with i get looks like a list of arrays, which includes object arrays, which include developer class objects and ProjectDeveloper (mtm class). Unfortunately I can not place a link with the image, but Schema look like:

developers = {ArrayList@4889} size = 4 
 \/ 0 = {object[2]4897} //what does this do in ArrayList<**Developer**>>??
    -> 0 = {Developer@4901} //This is exactly the class I expect in ArrayList
    -> 1 = {ProjectDeveloper}//?????
 -> 1 = {object[2]4898}

Developer class:

@Table(name = "developers")
@Entity
public class Developer implements GenerallyTable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;
    @Column(name = "first_name")
    private String name;     
    @Column(name = "age")
    private int age;     
    @Column(name = "sex")
    private boolean sex;    
    @Column(name = "salary")
    private BigDecimal salary;
//...getters + setters
}

How it impossible (how Developer.class transformed in array with unknown structure), and how do I can get exactly ArrayList of Developers?

Upvotes: 1

Views: 917

Answers (1)

Zeromus
Zeromus

Reputation: 4532

Try with createQuery with the type defined https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Session.html#createQuery-java.lang.String-java.lang.Class-

List<Developer> developers = session.createQuery("select d from Developer d " +
                    "left join ProjectDeveloper pd on pd.developer.id = d.id " +
                    "where pd.project.id = " + project.getId(), Developer.class)
                    .getResultList();

Also you should use setParameter methods

List<Developer> developers = session.createQuery("select d from Developer d " +
                    "left join ProjectDeveloper pd on pd.developer.id = d.id " +
                    "where pd.project.id = :proj_id", Developer.class)
                    .setParameter("proj_id", project.getId())
                    .getResultList();

Upvotes: 2

Related Questions