2014-05-12 51 views
1

我已經在這裏閱讀文章,但我不能得到解決我的問題How to get Id of last persisted entity using JPAJava的JPA獲得的最後一個ID堅持實體問題

我不能得到最後的自動遞增的學生

這是從的主鍵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,但每次添加student時它總是輸出0。我無法得到最後生成的id。任何幫助將不勝感激。謝謝!

編輯: 我的學生類別:

封裝模式;

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

- 已解決!由Peter回答,謝謝!

+0

您可以在這裏發佈您的學生課嗎? –

+0

也打印異常的堆棧跟蹤(應該發生異常,除非您正在做一些基本錯誤(如打印錯誤的變量))。 –

+0

我已添加學生類實體。 – MLDS

回答