简体   繁体   中英

Retrieve all primary keys using Java Persistence

I have a function "checkPatientId" that takes as argument a "patient_id" and returns "Valid" if the patient_id exists in the table "patient_personal_details" or returns "Invalid" if it doesn't exist.

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;
}

I want to know how to retrieve and check for a patient_id using Java Persistence instead of SQL. I have already generated my entity class and persistence unit and also established my database connection. PS I'm using Netbeans 8.0.2 Enterprise.

Entity objects can be uniquely identified and retrieved by using find() method of EntintyManager em Try it as: Patient patient= em.find(Patient.class, 1); where 1 is the primary key. it returns null if object is not found in the database.

Entity objects can be uniquely identified and retrieved by using

T getReference method of EntintyManager em 

Try it as:

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

where 1 is the primary key. It returns null if object is not found in the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM