【问题标题】:Retrieve specific table rows using Java Persistence使用 Java Persistence 检索特定的表行
【发布时间】:2015-05-03 02:13:09
【问题描述】:

我有一张表格 patient_details(patient_id, first_name, last_name, address,date_of_birth, gender, contact_number,occupation)。我已经生成了一个实体类和一个 PersistenceUnit。我只能使用它的 ID 找到一个对象:

PatientDetails pd = em.find(PatientDetails.class,patient_id);

我想知道如何使用其他列名而不是仅使用主键来查找对象。

【问题讨论】:

    标签: jpa persistence jpa-2.0 entitymanager java-ee-7


    【解决方案1】:
    【解决方案2】:

    例如:

    如果

    class PatientDetails
     String first_name;
     @Column(",date_of_birth")
     Date birth;
     ...
    }
    

    然后

    String sql = "SELECT p FROM PatientDetails p where p.first_name = :fname and p.birth > :generation";
    Date generation = new Date(int 1980, 0, 1);
    TypedQuery<PatientDetails> query = EM.createQuery(sql);
    query.setParameter("fname","John");
    query.setParameter("generation",generation);
    return query.getResultList
    

    返回名为 John 且出生于 1980 年之后的患者。

    但是你应该阅读@pL4Gu33推荐的链接

    【讨论】:

    • 我可以用 SELECT * 代替 p 吗?什么是“世代”及其目的?
    • 生成的目的从预期查询结果的描述中应该很明显了。
    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多