我在Spring Boot 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;
}
现在我需要为用户选择所有单词,但排除用户列表中的单词
user_id = 1的本机SQL是
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 Data功能或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 :(得分:0)
最快的答案是Criteria
api(但在hibernate 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();