Ankit Bansal
Ankit Bansal

Reputation: 2358

JPQL Join and class cast exception

I am using JPA with Hibernate in spring boot.

I have two jpa entities

@Entity
@Table(name="courses_type")
public class CoursesType implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private int id;

    @Column(name="course_id")
    private int courseId;

    @Column(name="level")
    private int level;

    private int credential;

    private String status;

    private String type;

    @Column(name="updated_by")
    private int updatedBy;

    @Column(name="updated_on")
    private Timestamp updatedOn;

    @ManyToOne(fetch=FetchType.LAZY, optional=false)
    @JoinColumn(name="credential", referencedColumnName="value_id",insertable=false,updatable=false)
    @Where(clause="status='live'")
    private BaseAttributeList credentialData;


    @ManyToOne(fetch=FetchType.LAZY, optional=false)
    @JoinColumn(name="level", referencedColumnName="value_id",insertable=false,updatable=false)
    @Where(clause="status='live'")
    private BaseAttributeList courseLevelData;

... setters and getters

}

Second Entity

@Entity
@Table(name="attribute_list")
public class AttributeList implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="value_id")
    private int valueId;

    private String status;

    @Column(name="value_name")
    private String valueName;



}

Now I am trying to write a JPQL Query in CourseTypeRepo

@Query("Select sct.courseId, sct.credential, sct.credentialData from CoursesType"
            + " sct where sct.courseId IN(?1) and sct.status = ?2")
    List<CoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);

Now when I am iterating the result, I am getting class Cast Exception that

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.domain.CoursesType

Basically what I am trying to fetch the complete data using one jpql query. How should I fix this?

Upvotes: 0

Views: 1160

Answers (1)

Cepr0
Cepr0

Reputation: 30484

If don't want to fetch full object but only some its properties you have to provide a projection then use it in your query method, for example:

public interface PartialCoursesType {

    Integer getCourseId(), 
    Integer getCredential(), 
    BaseAttributeList getCredentialData()
}

@Query("select sct.courseId as courseId, sct.credential as credential, sct.credentialData as credentialData...")
List<PartialCoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);

To make the trick works you have to use aliases in the query...

Upvotes: 1

Related Questions