父接口上的Spring Data JPA JPQL查询 [英] Spring Data JPA JPQL queries on parent interface
问题描述
说我有一个像这样的@MappedSuperClass
:
@MappedSuperclass
public abstract class Rating
{
@Id
private Long id;
@Column(name="USER_ID")
private Long userId;
private int rating;
...
具有这样的具体子实体
@Entity
@Table(name="ACTIVITY_RATING")
public class ActivityRating extends Rating
{
private Long activitySpecificData;
...
然后有一个像这样的Spring Data JPA存储库:
Then there is a Spring Data JPA repository like this:
@NoRepositoryBean
public interface RatingRepository<R extends Rating> extends JpaRepository<R, ID>
{
public List<R> findByUserId(Long userId);
...
和这个:
public interface ActivityRatingRepository extends RatingRepository<ActivityRating>
{
}
这一切都很好,我可以在扩展RatingRepository
的任何特定评级存储库中调用findByUserId()
.我现在想在所有子接口都可以继承的RatingRepository
中编写一些JPQL.我只是不知道在查询中FROM
之后要放什么(或什至有可能).例如:
This all works great and I can call findByUserId()
on any of specific rating repositories that extend RatingRepository
. I am now wanting to write some JPQL in the RatingRepository
that all the child interfaces can inherit. I just don't know what (or if it's even possible) to put after the FROM
in the query. For example:
@Query("SELECT NEW com.foo.RatingCountVo(e.rating, COUNT(e.rating)) FROM ??????? e GROUP BY e.rating")
public List<RatingCountVo> getRatingCounts();
我可以将此方法添加到扩展RatingRepository
的每个单独的存储库中,但是除了特定的实体名称之外,其他所有内容都将完全相同.如果要更改查询,则必须转到所有子存储库并分别进行更新.我真的希望查询生活在父类中,而不是重复的.有什么办法可以做到这一点?
I can add this method to each of the individual repositories that extend RatingRepository
but everything would be exactly the same except for the specific entity name. If I want to change the query, I'd then have to go to all the child repositories and update them individually. I really want the query to live in the parent class and not be duplicated. Is there any way to accomplish this?
我目前正在使用spring-data-jpa 1.7.2和eclipselink 2.5.2.我不一定非要在必要时切换到较新版本.
I'm currently using spring-data-jpa 1.7.2 and eclipselink 2.5.2. I'm not necessarily opposed to switching to newer versions if necessary.
推荐答案
如果将查询分为三个部分,它将开始工作吗:查询的开始,实体和结束?然后,如果可以的话,在每个接口中定义
Will it work if you will split query into 3 parts: start, entity and end of query? Than, if it'll work, in each interface you define constant like
String ENTITY = "ActivityRating";
然后您可以像使用它
@Query(RatingRepository.QUERY_START + ENTITY + RatingRepository.QUERY_END)
List<RatingCountVo> getRatingCounts();
顺便说一句,不需要在界面中定义public修饰符.
BTW, there is no need to define public modifier in interface.
更新:此处描述的另一种方式:
@Query("SELECT NEW com.foo.RatingCountVo(e.rating, COUNT(e.rating)) FROM #{#entityName} e GROUP BY e.rating
这篇关于父接口上的Spring Data JPA JPQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!