我正在编写一个springBoot应用程序,有3个类:
@Table(name = "notification")
public class Notification{
@Id
@Column("notification_id")
// generateStrategy
long id;
@ManyToMany
List<Role> roles;
@ManyToMany
List<User> users;
}
字符串
另一类:
public class Role{
\\ id and some other fields.
}
型
User类是相同的。通知和角色之间的关系是单向的。(通知和用户也是如此)
现在,我正在使用hibernate来持久化数据库中的数据。
我的问题是如何检索具有给定角色的所有通知?例如,我有一个“admin”角色(这是一个对象!),我想在他们的“角色”列表中找到所有包含“admin”的通知。
可以用Hibernate自己写吗?(我知道当我们在数据库接口中以特定格式编写函数名时,hibernate能够生成sql代码)。
如果不可能,我如何手动编写高效SQL查询?
2条答案
按热度按时间e0bqpujr1#
有多种方式可以考虑,让我们尝试分解每一种:
使用JPQL
字符串
使用Spring Data JPA方法命名
型
使用Criteria API
(more构造查询的详细和编程方法)
型
基本上,你可以选择任何一个。如果您更喜欢声明性的方法和简单性,那么推荐使用前两种方法。如果您需要一种动态的编程方法,那么API将是您的选择
ix0qys7i2#
假设你有一个这样的角色实体:
字符串
要获取所有在其角色列表中包含特定角色的通知,您只需在JpaRepository中定义一个方法,如下所示:
型
并在服务中调用该方法,如下所示:
型