这是我的存储库:
@Repository
public interface EventRepository extends JpaRepository<Events, Long>, JpaSpecificationExecutor<Events>{
@Query(value=" SELECT DISTINCT event.EVENT_ID "
+ "FROM EVENTS event "
+ "JOIN EVENTS event2 "
+ "ON event.EVENT_ID = event2.PARENT_ID "
+ "WHERE event.ENTITY_ID IN (?1)", nativeQuery = true)
List<Long> getDescendantEventIdInEntityId(Set<Long> descendantEntities);
}
为什么调用此方法时,它会返回: 内部异常:java.sql.SQLException:Tipo di colonna non valido 错误代码:17004 调用:SELECT DISTINCT event.EVENT_ID FROM EVENTS事件JOIN EVENTS event2 ON event.EVENT_ID = event2.PARENT_ID WHERE event.ENTITY_ID IN(?) bind =&gt; [[1]]
查询有什么问题? 如果查询没问题,那就是&#34; bind =&gt; [[1]]&#34;真正的问题?如果是的话,为什么方括号太多了?
我也试过这个解决方案:
@Query(value=" SELECT DISTINCT event2.EVENT_ID "
+ "FROM EVENTS event "
+ "JOIN EVENTS event2 "
+ "ON event.EVENT_ID = event2.PARENT_ID "
+ "WHERE event.ENTITY_ID IN :entitiesId", nativeQuery = true)
List<Long> getDescendantEventIdInEntityId(@Param("entitiesId") Set<Long> entitiesId);
但它又给我一个错误: 索引:: 1处缺少IN或OUT参数 错误代码:17041 调用:SELECT DISTINCT event2.EVENT_ID FROM EVENTS事件JOIN EVENTS event2 ON event.EVENT_ID = event2.PARENT_ID WHERE event.ENTITY_ID IN:entitiesId
解决方案:解决了从EntityManager创建新的nativeQuery:
em.createNativeQuery(" SELECT DISTINCT event2.EVENT_ID "
+ "FROM EVENTS event "
+ "JOIN EVENTS event2 "
+ "ON event.EVENT_ID = event2.PARENT_ID "
+ "WHERE event.ENTITY_ID IN ("+idList+") AND event.STATUS = 2")
.getResultList();
其中idList是StringUtils.join制作的String(CollectionOfId,&#34;,&#34;);
答案 0 :(得分:2)
如果Hibernate用作JPA提供程序,而不是位置参数绑定(?1
),您还可以使用命名参数绑定(:parameterName
)。这样可以减少错误,你可以省略括号,让Spring管理你的语法。你也不需要自己解析任何东西。
使用命名参数绑定,如:
@Query(value="SELECT DISTINCT event2.EVENT_ID "
+ "FROM EVENTS event "
+ "JOIN EVENTS event2 "
+ "ON event.EVENT_ID = event2.PARENT_ID "
+ "WHERE event.ENTITY_ID IN :entityIds", nativeQuery = true)
List<Long> getDescendantEventIdInEntityId(@Param("entityIds") Set<Long> ids);
在这两种情况下,请注意将null或空集传递给方法!这可能会导致不可预测的结果。
可悲的是,命名参数不是JPA标准,也许EclipseLink不支持它(以这种方式)。然后你必须使用位置参数。