轻松的生活!
现在,查询选择分数,只加入一些用户,但不真正加入获取
Score.users
或
user.score
协会。如果希望同时加载score和关联用户,则需要执行以下操作:
正如我在
this article
可以使用窗口函数。
MySQL 8 supports Windows Functions
所以只需运行以下SQL查询:
List<Score> scores = entityManager.createNativeQuery(
"select u_s_r.* " +
"from ( " +
" select *, dense_rank() OVER (ORDER BY value DESC) rank " +
" from ( " +
" select s.*, u.* " +
" from scores s " +
" join users u s.user_id = u.id " +
" order by u.id " +
" ) u_s " +
") u_s_r " +
"where u_s_r.rank <= :rank", Score.class)
.setParameter("rank", 10)
.unwrap( NativeQuery.class )
.addEntity( "s", Score.class )
.addEntity( "u", User.class )
.setResultTransformer( DistinctScoreResultTransformer.INSTANCE )
.getResultList();
这个
DistinctScoreResultTransformer
可以看如下:
public class DistinctScoreResultTransformer
extends BasicTransformerAdapter {
private static final DistinctScoreResultTransformer INSTANCE =
new DistinctScoreResultTransformer();
@Override
public List transformList(List list) {
Map<Serializable, Identifiable> identifiableMap =
new LinkedHashMap<>( list.size() );
for ( Object entityArray : list ) {
if ( Object[].class.isAssignableFrom(
entityArray.getClass() ) ) {
Score score = null;
User user = null;
Object[] tuples = (Object[]) entityArray;
for ( Object tuple : tuples ) {
if(tuple instanceof Score) {
score = (Score) tuple;
}
else if(tuple instanceof User) {
user = (User) tuple;
}
else {
throw new UnsupportedOperationException(
"Tuple " + tuple.getClass() + " is not supported!"
);
}
}
Objects.requireNonNull(score);
Objects.requireNonNull(user);
if ( !identifiableMap.containsKey( score.getId() ) ) {
identifiableMap.put( score.getId(), score );
score.setUsers( new ArrayList<>() );
}
score.addUser( user );
}
}
return new ArrayList<>( identifiableMap.values() );
}
}
如果你想知道这是否可以通过JPQL来完成,那么你应该知道这是不可能的。但是,您不必通过jpql运行每个查询。
Native SQL is the Magic Wand
在数据访问层工具箱中。