2017-10-15 29 views
1

我在春天启动v1.5.7应用如何通过另一台由不相容原理过滤器中选择从表

我有3个实体(示意图):

@Entity 
public class Word { 
    @Id 
    @GeneratedValue 
    private Integer id 
    ... 
} 

@Entity 
public class UserWordList { 
    @Id 
    @GeneratedValue 
    private Integer id 

    @ManyToOne 
    @JoinColumn(name = "user_id") 
    private User user; 

    @ManyToOne 
    @JoinColumn(name = "word_id") 
    private Word word; 
} 

@Entity 
public class UserAnotherWordList { 
    @Id 
    @GeneratedValue 
    private Integer id 

    @ManyToOne 
    @JoinColumn(name = "user_id") 
    private User user; 

    @ManyToOne 
    @JoinColumn(name = "word_id") 
    private Word word; 
} 

现在我需要选择所有关键词对于用户,但不包括放置在用户的列表

本机SQL为USER_ID字= 1是

select * 
from Word w 
left join UserWordList uwl 
    on w.id = uwl.word_id and uwl.user_id = 1 
left join UserAnotherWordList uawl 
    on w.id = uawl.word_id and uawl.user_id = 1 
where uwl.word_id is NULL 
and uawl.word_id is NULL 

什么是最好的方式来做到这一点?理想情况下,我想使用Spring数据功能或HQL,但我不知道如何...

UPD

我解决我的本地查询问题:

@Entity 
@NamedNativeQuery(
    name = "User.getWordsToProcess", 
    resultClass = Word.class, 
    query = "<...native query to select Words...>" 
) 
public class User {...} 

... 

public interface UserRepository extends CrudRepository<User, Integer> { 
    List<Word> getWordsToProcess(Integer userId); 
} 

回答

0

最快的答案是Criteria API(但在休眠5.2及以上不建议使用。) 所以,你可以使用HQL:

getSession().createQuery(" select * from UserWordList u left join fetch u.word 
left join fetch u.user").list() 

并且您可以使用union或创建另一个查询来获取UserAnotherWordList。 你也可以在Hql中设置如下限制:

Query query = getSession().createQuery(" select * from UserWordList u left join fetch u.word left join fetch u.user us where us.user = :sample").list(); 
query.setParameter("sample",value); 
query.list();