Spring JPA:在同一查询界面上使用多个投影 [英] Spring JPA: Using multiple projection on same query interface
问题描述
我正在尝试使用Spring JPA的投影从查询结果中过滤掉不必要的数据。但是,我有多个投影需要在同一个接口方法上使用。
I am trying to use Spring JPA's projection to filter out unnecessary data from query result. However, I have multiple projections that will need to be used on the same interface method.
问题是,我试图用不同的方法从同一个方法查询数据返回对象,但java不允许这样做。
The problem is, I am trying to query data from the same method with a different returning object but java doesn't allowed this.
JPA根据方法名称自动生成查询,因此我无法更改方法名称。
The query are auto generated by JPA based on method name, so I cannot make changes to method name.
除了创建新界面之外,还有其他选择吗,因为我认为这是一个麻烦且不必要的
Is there a alternative, other than creating a new interface, since I think it's a hassle and unnecessary
这里有一个示例代码,我想做的。
here is a sample code, of what I am trying to do.
自动生成查询
Auto-Generated Query
public interface UserRepository extends CrudRepository<UserAccount, Long> {
AuthenticateProjection getByUsername(String username);
UserDetailsProjection getByUsername(String username);
}
预测
Projections
public interface AuthenticateProjection {
@Value("#{target.username}")
String getUsername();
@Value("#{target.credentail.token}")
String getHashPassword();
}
public interface UserDetailsProjection {
@Value("#{target.username}")
String getUsername();
@Value("#{target.firstname}")
String getFirstName();
@Value("#{target.lastname}")
String getLastName();
}
推荐答案
所以我成功了弄清楚如何使用单个查询使用多个投影。
So I've managed to figure out how to use multiple projections with a single query.
<T> T getByUsername(String username, Class<T> projection)
这允许方法调用者指定类型要应用于查询的投影。
This allows the method caller to specified the type of projection to be applied to the query.
为了进一步改进这一点,它不容易出错,我做了一个空白界面,投影必须按顺序扩展能够将类插入参数。
To further improve this so it is less prone to error, I made a blank interface that the projection will have to extend in order to be able to insert class into the parameter.
public interface JPAProjection {
}
public interface UserRepository extends CrudRepository<UserAccount, Long> {
<T extends JPAProjection > T getByUsername(String username, Class<? extends JPAProjection> projection);
}
投影界面
Projection Interface
public interface UserDetailsProjection extends JPAProjection{
@Value("#{target.username}")
String getUsername();
@Value("#{target.firstname}")
String getFirstname();
@Value("#{target.lastname}")
String getLastname();
}
然后我可以通过
getByUsername("...", UserDetailsProjection.class)
这篇关于Spring JPA:在同一查询界面上使用多个投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!