当前位置: 首页 > 知识库问答 >
问题:

Spring数据投影和错误:“在结果元组中没有找到别名!确保您的查询定义了别名!”

齐鹏程
2023-03-14

下面从JPA查询中获取Spring数据投影的方法对我不起作用:

https://stackoverflow.com/a/45443776/1005607

id   description    display_order_num
------------------------------------
1    Category #1    1
2    Category #2    2
id  activity_category_id  activity_title
---------------------------------------
1      2                  Sleeping
2      2                  Eating
3      2                  Travel
@Repository
public interface ActivitiesDAO extends JpaRepository<ActivitiesT, Integer> {

    @Query("select a.activityTitle, l.description as category, " + 
           "l.displayOrderNum as categoryDisplayOrderNum " + 
           "from ActivitiesT a, LookupT l " + 
           "where a.lookupT.id = l.id order by l.displayOrderNum asc ")
    public List<MySpringDataProjection> findCustom();

}

Spring数据投影模型界面:

public interface MySpringDataProjection {

    public String getActivityTitle();

    public String getCategory();

    public Integer getCategoryDisplayOrderNum();

}

一切都和那个公认的答案一样。但是得到这个错误:

org.springframework.dao.InvalidDataAccessApiUsageException: No aliases found in result tuple! Make sure your query defines aliases!; nested exception is java.lang.IllegalStateException: No aliases found in result tuple! Make sure your query defines aliases!
    org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:489)
    org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)

我不想在查询中使用select new Obj(..),它很脏,依赖于我们将其抽象为JPA的Hibernate。

共有1个答案

公冶嘉
2023-03-14

我遇到同样的问题。在尝试了几个更改之后,我发现我们只需要为NativeQuery中的每个列添加“as”(即使列名也没有更改)。对于这里的您,更改您的sql,如下所示:

    @Query("select a.activityTitle **as activityTitle**, l.description as category, " + 
       "l.displayOrderNum as categoryDisplayOrderNum " + 
       "from ActivitiesT a, LookupT l " + 
       "where a.lookupT.id = l.id order by l.displayOrderNum asc ")
 类似资料: