[英]Java JPA get id of last persisted entity issue
I have read the article here but I cannot get fix my problem How to get Id of last persisted entity using JPA 我已经在这里阅读了文章,但无法解决我的问题如何使用JPA获取上一个持久实体的ID
I cannot get the last auto incremented primary key of the student 我无法获取学生的最后一个自动递增的主键
This is from the Servlet class 这是来自Servlet类
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: 这是来自会话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
. 我只是用sout进行测试,看是否获得了ID
但是每次添加一个student
时,它始终输出0
。 I cannot get the last generated id
. 我无法获取最后生成的id
。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!
EDITED: My Student Class: 编辑:我的学生班:
package model; 包装型号;
import javax.persistence.*; 导入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! 彼得回答,谢谢!
Id is incremented in your db? ID在您的数据库中递增? Maybe you forgot @GeneratedValue annotation above your id definition. 也许您忘记了ID定义上方的@GeneratedValue批注。 Check this: http://www.objectdb.com/java/jpa/entity/generated 检查此: http : //www.objectdb.com/java/jpa/entity/generated
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.