Reputation: 83
I have read the article here but I cannot get fix my problem How to get Id of last persisted entity using JPA
I cannot get the last auto incremented primary key of the student
This is from the Servlet class
if (operation.equalsIgnoreCase("Add")) {
student.setName(name);
student.setAddress(address);
int last = studentDAO.addStudent(student);
request.setAttribute("last", last);
request.setAttribute("student", student);
}
This is from the session bean:
public int addStudent(Student student) {
em.persist(student);
em.flush();
System.out.println(student.getStudentID());
return student.getStudentID();
}
I just used sout to test and see if I got the ID
but it always outputs 0
every time I add a student
. I cannot get the last generated id
. Any help would be greatly appreciated. Thanks!
EDITED: My Student Class:
package model;
import javax.persistence.*;
@Entity
@Table
@NamedQueries({@NamedQuery(name="Student.getAll", query="Select e from Student e")})
public class Student {
@Id
@Column
private int studentID;
@Column
private String name;
@Column
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public Student(int studentID, String name, String address) {
this.studentID = studentID;
this.name = name;
this.address = address;
}
public Student(){}
}
--Solved! Answered by Peter, Thank you!
Upvotes: 1
Views: 912
Reputation: 314
Id is incremented in your db? Maybe you forgot @GeneratedValue annotation above your id definition. Check this: http://www.objectdb.com/java/jpa/entity/generated
Upvotes: 1