【问题标题】:Retrieve all primary keys using Java Persistence使用 Java Persistence 检索所有主键
【发布时间】:2015-05-02 15:41:51
【问题描述】:

我有一个函数“checkPatientId”,它接受一个“patient_id”作为参数,如果 patient_id 在“patient_personal_details”表中存在则返回“Valid”,如果不存在则返回“Invalid”。

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 Enterprise。

【问题讨论】:

  • 以上代码是测试代码还是你的代码?
  • WHERE patient_id = ? 添加到您的SQL 并使用patient_id 作为查询参数。

标签: java jpa persistence jpa-2.0 entitymanager


【解决方案1】:

Entity对象可以通过EntintyManager的find()方法进行唯一标识和检索em尝试如下:Patient patient= em.find(Patient.class, 1);其中1是主键。如果在数据库中找不到对象,则返回 null。

【讨论】:

    【解决方案2】:

    实体对象可以通过使用来唯一标识和检索

    T getReference method of EntintyManager em 
    

    试一试:

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

    其中 1 是主键。如果在数据库中找不到对象,则返回null

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 2015-05-03
      • 2018-10-06
      • 1970-01-01
      • 2012-10-09
      • 2017-10-23
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多