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

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();

}
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)

共有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 ")
 类似资料: