以下从JPA查询获取Spring Data Projection的方法对我来说不起作用:
https://stackoverflow.com/a/45443776/1005607
我的表:
LOOKUP_T
id description display_order_num
------------------------------------
1 Category #1 1
2 Category #2 2
ACTIVITIES_T(activity_category_id映射到LOOKUP_T.id)
id activity_category_id activity_title
---------------------------------------
1 2 Sleeping
2 2 Eating
3 2 Travel
Spring Data DAO接口,用于从此连接中获取某些字段:
@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 Data Projection Model接口:
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(..)
,它很脏并且依赖于Hibernate,而我们正在将其抽象为JPA。
我想让这种投影方法起作用。
我引用的(非工作)答案的相关问题, Spring data JPA: getting No aliases found in result tuple! error when executing custom query
答案 0 :(得分:7)
我遇到同样的问题。在尝试了几次更改之后,我发现我们只需要在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 ")
答案 1 :(得分:2)
我认为你必须在界面中定义确切的名称方法,但我不确定这种方法适用于你的情况。
这里重要的一点是,此处定义的属性与聚合根中的属性完全匹配。这允许像这样添加查询方法
在您的示例中,您可以尝试Open Projection
答案 2 :(得分:2)
我有同样的问题,我想我解决了。我所做的是在所有字段中使用别名,即使它们具有相同的名称。在activityTitle中也使用别名。像这样:
@Repository
public interface ActivitiesDAO extends JpaRepository<ActivitiesT, Integer> {
@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 ")
public List<MySpringDataProjection> findCustom();
}