【问题标题】:I create a query on a method that is an object and I don't know how how to make it return the object我在作为对象的方法上创建了一个查询,但我不知道如何让它返回该对象
【发布时间】:2021-12-26 17:49:38
【问题描述】:

我一直在搜索,但我的问题没有找到答案。

我有以下代码:

public ScriptInfo findByForeignKey(int id) {
    Session currentSession = entityManager.unwrap(Session.class);
        
    Query<ScriptInfo> theQuery =
        currentSession.createQuery("Select *
        from SCRIPT_INF AND SPRINT
        where FK_ID_SPRINT=:idSprint
        AND FK_ID_SPRINT=SPRINT.ID_SPRINT");
        
    theQuery.setParameter("idSprint", id);
        
}

我不知道如何放置返回,所以它返回对象ScriptInfo 过滤。

【问题讨论】:

  • 在你创建的对象上添加return语句。

标签: hibernate jpa return


【解决方案1】:

Query 提供了多种获取查询结果的方法:

  • getResultList()
  • getFirstResult()
  • getSingleResult()

正确的取决于您所期望和想要返回的内容。 它们各自的行为在JavaDoc of Query 中进行了描述。 为了让它们正常工作,您需要提供您希望查询返回的类的信息,方法是将其作为参数添加到 createQuery

您的最终代码看起来与此有些相似:

public ScriptInfo findByForeignKey(int id) {
        
    Query<ScriptInfo> theQuery = entityManager.createQuery("select si from ScriptInfo si where si.sprint.id = :idSprint", ScriptInfo.class);
        
    theQuery.setParameter("idSprint", id);   

    return theQuery.getFirstResult();     
}

注1:

您使用 createQuery 需要 HQL 或 JPQL 查询,但您传入的似乎是 SQL。 这行不通。 使用createSQLQuery() 或改用JPQL。 我推荐后者,因为我认为只有在无法使用 JPQL 表达查询时才应该使用 SQL。 当您在转换方面需要帮助时,请随意创建一个新问题。 只需确保包含您的域模型即可。

注2:

您不需要unwrap 来自EntityManagerSession。 您在Session 中使用的所有功能也可在EntityManager 中使用。只有createSQLQuery 被命名为createNativeQuery

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2021-10-13
    • 2014-04-02
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多