This is my tables:
@Entity
@Table(name="Students") public class Students {
@Id
@Column(name="Student_ID")
private int id;
@Column(name="Student_Name")
private String name;
@Column(name="Email_ID")
private String emailId;
@Column(name="Phone_no")
private long phoneNo;
@Column(name="Class_ID")
private int classId;
@Column(name="DOB")
private Date dob;
and
@Entity
@Table(name="Assigned") public class Assign {
@Id
@Column(name="Assign_ID")
private int aId;
@Column(name="Class_ID")
private int classId;
@Column(name="Teacher_ID")
private int tId;
@Column(name="Subject_ID")
private int sId;
When I run this code :
PrintWriter out = response.getWriter();
out.append("<html><body>");
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List<Subjects> subjects = session.createQuery(" from Subjects").list();
out.println("<h1> Students List :-");
out.println("<table>");
out.println("<tr>");
out.println("<th> Subject Id </th>");
out.println("<th> Subject Name </th>");
out.println("</tr>");
for(Subjects subject : subjects ) {
out.println("<tr>");
out.println("<td>" subject.getsId() "</td>");
out.println("<td>" subject.getsName() "</td>");
out.println("</tr>");
}
out.println("</table>");
out.append("</body></html>");
It works just fine But when I try to run this:
PrintWriter out = response.getWriter();
out.append("<html><body>");
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List<Subjects> subjects = session.createQuery("from Subjects s, Assign a where s.sId = a.sId and a.classId = 2").list();
out.println("<h1> Students List :-");
out.println("<table>");
out.println("<tr>");
out.println("<th> Subject Id </th>");
out.println("<th> Subject Name </th>");
out.println("</tr>");
for(Subjects subject : subjects ) {
out.println("<tr>");
out.println("<td>" subject.getsId() "</td>");
out.println("<td>" subject.getsName() "</td>");
out.println("</tr>");
}
out.println("</table>");
out.append("</body></html>");
it gives this error : java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class entity.Subjects ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; entity.Subjects is in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @7aeb7c5e)
I didn't do @Manytoone Annotation as I read here( How to make this select * from two joined tables query in HQL form?) you can also work without them.
I have tried various things but to no avail. Can someone please tell me why this is happening and how to fix this?
CodePudding user response:
explicit cast is needed, so use the code below instead:
List<Subjects> subjects =
session.createQuery(
"select s from Subjects s, Assign a where s.sId = a.sId and
a.classId = 2", Subjects.class).list();