Spring Data JPA:使用@Query Annotation检查是否存在实体ID

时间:2016-05-25 11:15:15

标签: java hibernate jpa

我正在尝试使用简单的JPQL来检查是否存在实体ID。

我的PlanDetail实体:

Entity
@Table(name="T_PLAN_DETAIL")
public class PlanDetail extends AbstractProcessEntity {

@ManyToOne
@JoinColumn(name = "TERRITORY_ID")
private Territory territory;
...
}

我想使用Assert检查它:

Assert.isTrue(planDetailRepository.existsByTerritory(territoryId), "This territory exist with ID = " + territoryId);

我的PlanDetail实体:

public interface PlanDetailRepository extends CrudRepository<PlanDetail, Long> {

@Query("SELECT COUNT(e)>0 FROM PlanDetail e WHERE e.terrritoryId=?1")
boolean existsByTerritory(Long territoryId);
}

错误日志:

Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: terrritoryId of: test.domain.model.plan.PlanDetail [SELECT COUNT(e)>0 FROM test.domain.model.plan.PlanDetail e WHERE e.terrritoryId=?1]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1750) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:331) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]

感谢任何帮助。你能告诉我任何JPQL文件..谢谢。

1 个答案:

答案 0 :(得分:1)

假设您的区域实体有一个名为&#34; id&#34;。

的字段

将您的查询更改为:

@Query("SELECT COUNT(e)>0 FROM PlanDetail e WHERE e.territory.id=?1")