Java JPA获取最后一个持久化实体问题的ID

时间:2014-05-12 11:52:16

标签: java jpa entity

我在这里阅读了这篇文章,但我无法解决问题How to get Id of last persisted entity using JPA

我无法获得学生的最后一个自动递增的主键

这是来自Servlet类

if (operation.equalsIgnoreCase("Add")) {
            student.setName(name);
            student.setAddress(address);


            int last = studentDAO.addStudent(student);
            request.setAttribute("last", last);
            request.setAttribute("student", student);

        }

这是来自会话bean:

public int addStudent(Student student) {
        em.persist(student);

        em.flush();

        System.out.println(student.getStudentID());
        return student.getStudentID();
    }

我刚刚使用sout进行测试,看看我是否得到ID,但每次添加0时都会输出student。我无法获得最后生成的id。任何帮助将不胜感激。谢谢!

EDITED: 我的学生班:

包装模型;

导入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(){}
}

- 解决了!彼得回答,谢谢!

1 个答案:

答案 0 :(得分:1)

您的数据库中的ID会增加吗?也许你忘记了id定义之上的@GeneratedValue注释。 检查一下:http://www.objectdb.com/java/jpa/entity/generated