1fuyouinfinite
1fuyouinfinite

Reputation: 1

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. P.S I'm using Netbeans 8.0.2 Enterprise.

Upvotes: 1

Views: 557

Answers (2)

Navnath Chinchore
Navnath Chinchore

Reputation: 95

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.

Upvotes: 0

Abhi
Abhi

Reputation: 341

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.

Upvotes: 1

Related Questions