Reputation: 3
I am trying to execute a JPA program in eclipse. I have imported all necessary packages.
This is my POJO(@entity) class
@Entity
public class Student
{
int id,marks;
String name;
Student(int i, int j, String k)
{
id=i;marks=j;name=k;
}
public int getMarks()
{
return marks;
}
public void setMarks(int i)
{
marks = i;
}
}
This is a portion of my 'main' class
EntityManagerFactory emf = Persistence.createEntityManagerFactory("database/database.odb");
EntityManager em = emf.createEntityManager();
Student s1;
em.getTransaction().begin();
s1 = new Student(1,100,"abcd");
em.persist(s1);
s1 = new Student(2,200,"efgh");
em.persist(s1);
s1 = new Student(3,300,"ijkl");
em.persist(s1);
em.getTransaction().commit();
Query q1 = em.createQuery("select marks from Student");
List<Student> result = q1.getResultList();
em.getTransaction().begin();
for(Student s : result)
{
if(s.getMarks()%200==0)
em.remove(s);
else
s.setMarks(s.getMarks()*2);
}
em.getTransaction().commit();
q1 = em.createQuery("select marks from Student");
System.out.println("Details of students are : " + q1.getResultList());
The output i expect is : [200, 600] because the marks in the 1st and 3rd record should get multiplied by 2 and the the 2nd record should get deleted.
But I get an error :
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to assg6.Student at assg6.Main.main(Main.java:52)
(My project's package name is assg6)
I tried this
List<Student> result = (List<Student>)q1.getResultList();
and
for(Student s : (List<Student>)result)
Why am I not getting the expected output and how do i get it?
Upvotes: 0
Views: 56
Reputation: 1425
Apparently, q1.getResultList()
is returning a list of Integers. Not surprising, since you're saying Query q1 = em.createQuery("select marks from Student");
You probably wanted to write "select s from Student s"
instead.
Upvotes: 1