如何从JPA存储库返回特定属性?

时间:2014-10-23 12:35:32

标签: jpa repository

在将实体检索到资源时,我收到了ClassCastException。仅当JPA存储库语句显式指定要返回的属性时才会发生。

例如,这很好用,没有触发异常:

@Query("SELECT r FROM Rollout r, RolloutAdmin ra WHERE r.id = ra.rollout.id AND ra.admin = :admin")

它呈现为:

select rollout0_.id as id1_8_, rollout0_.version as version2_8_, rollout0_.bts_nb_all as bts_nb_a3_8_, rollout0_.country_id as country_9_8_, rollout0_.creation_datetime as creation4_8_, rollout0_.description as descript5_8_, rollout0_.end_datetime as end_date6_8_, rollout0_.name as name7_8_, rollout0_.operator_id as operato10_8_, rollout0_.start_datetime as start_da8_8_ from rollout rollout0_ cross join rollout_admin rolloutadm1_ where rollout0_.id=rolloutadm1_.rollout_id and rolloutadm1_.admin_id=1 order by rollout0_.name asc limit 10;

但是这会触发异常:

@Query("SELECT DISTINCT r.id, r.country, r.operator, r.name, r.description, r.creationDatetime, r.startDatetime, r.endDatetime FROM Rollout r, RolloutAdmin ra, BTS b WHERE b.rollout.id = r.id AND r.id = ra.rollout.id AND ra.admin = :admin GROUP BY r.id")

它呈现为:

select distinct rollout0_.id as col_0_0_, rollout0_.country_id as col_1_0_, rollout0_.operator_id as col_2_0_, rollout0_.name as col_3_0_, rollout0_.description as col_4_0_, rollout0_.creation_datetime as col_5_0_, rollout0_.start_datetime as col_6_0_, rollout0_.end_datetime as col_7_0_, country3_.id as id1_4_0_, operator4_.id as id1_6_1_, country3_.version as version2_4_0_, country3_.code as code3_4_0_, country3_.list_order as list_ord4_4_0_, country3_.name as name5_4_0_, operator4_.version as version2_6_1_, operator4_.country_id as country_9_6_1_, operator4_.description as descript3_6_1_, operator4_.image as image4_6_1_, operator4_.messenger as messenge5_6_1_, operator4_.name as name6_6_1_, operator4_.operator_id as operator7_6_1_, operator4_.url as url8_6_1_ from rollout rollout0_ inner join country country3_ on rollout0_.country_id=country3_.id inner join operator operator4_ on rollout0_.operator_id=operator4_.id cross join rollout_admin rolloutadm1_ cross join bts bts2_ where bts2_.rollout_id=rollout0_.id and rollout0_.id=rolloutadm1_.rollout_id and rolloutadm1_.admin_id=1 group by rollout0_.id order by rollout0_.name asc limit 10;

怎么会有这样的差异?在不获取整个依赖父属性的情况下指定要返回的属性的任何方法吗?

编辑:我现在理解,感谢Nizet,我需要返回与我的存储库方法相同类型的对象。

1 个答案:

答案 0 :(得分:1)

这很简单:

SELECT r FROM Rollout r

表示:我希望此查询返回类型为Rollout的r。查询返回List<Rollout>

SELECT DISTINCT r.id, r.country, r.operator, r.name, r.description, r.creationDatetime, r.startDatetime, r.endDatetime FROM Rollout r

意味着:我希望这个查询返回许多不同的东西:一个ID,一个国家,一个运算符等等。因为查询返回了许多不同的东西,不同的类型,并且可能来自几个不同的实体(不是这个例子)具体示例,但您也可以从ra返回属性,查询返回List<Object[]>,其中对象数组的第一个元素是ID,第二个是国家,第三个是运算符等

即便是您的第一个查询也比它应该更复杂。两个实体之间的关联已经说明了两个实体是如何连接的。所以你需要的只是

SELECT r FROM RolloutAdmin ra join ra.rollout r WHERE ra.admin = :admin