2015-03-02 106 views
1

我有一個函數「checkPatientId」是把參數作爲一個「patient_id」,並返回「有效」如果表中的「patient_personal_details」存在patient_id或返回「無效的」,如果它不檢索所有主鍵存在。使用Java持久性

public String checkPatientID(int patient_id) throws RemoteException{ 
    String result = "Valid"; 
    try{ 
     Class.forName("com.mysql.jdbc.Driver"); 
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost/hospital_database","root",""); 
     String sql = "SELECT patient_id FROM patient_personal_details"; 
     Statement s = con.createStatement(); 
     s.execute(sql); 
     ResultSet rs = s.getResultSet(); 

     if(rs!=null){ 
      while(rs.next()){ 
       int num = rs.getInt(1); 
       if(num == patient_id){ 
        result = "Invalid"; 
       } 
      } 
     } 
    } 
    catch(SQLException e){ 
     System.out.println("Error: "+e); 
    } 
    catch(ClassNotFoundException e){ 
     System.out.println("Error: "+e); 
    } 
    return result; 
} 

我想知道如何使用Java Persistence而不是SQL來檢索並檢查patient_id。我已經生成了我的實體類和持久性單元,並建立了我的數據庫連接。 P.S我使用NetBeans 8.0.2企業。

+0

上面的代碼測試代碼或您的代碼? – Ajit 2015-03-02 10:18:22

+0

添加'WHERE patient_id =?'你的SQL和使用'patient_id'作爲查詢的參數。 – 2015-03-02 10:22:29

回答

1

Entity對象可以通過使用find() EntintyManager em的方法唯一標識和檢索嘗試它:Patient patient= em.find(Patient.class, 1);其中1是主鍵。如果在數據庫中找不到對象,它將返回null。

0

實體對象可以被唯一地標識和檢索通過使用

T getReference method of EntintyManager em 

嘗試爲:

Patient patient= em.getReference(Patient.class, 1); 

其中1是主鍵。它返回null如果對象未在數據庫中找到。