如何使用hibernate和critria获取数据库中的所有实体?

niknxzdl  于 2023-08-06  发布在  其他
关注(0)|答案(2)|浏览(99)

我正在编写一个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查询?

e0bqpujr

e0bqpujr1#

有多种方式可以考虑,让我们尝试分解每一种:

使用JPQL

@Query("SELECT n FROM Notification n JOIN n.roles r WHERE r.name = :roleName")
List<Notification> findNotificationsByRoleName(@Param("roleName") String roleName);

字符串

使用Spring Data JPA方法命名

List<Notification> findByRolesName(String roleName);

使用Criteria API

(more构造查询的详细和编程方法)

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Notification> cq = cb.createQuery(Notification.class);
Root<Notification> notificationRoot = cq.from(Notification.class);
Join<Notification, Role> roleJoin = notificationRoot.join("roles");

Predicate roleNamePredicate = cb.equal(roleJoin.get("name"), "admin");
cq.where(roleNamePredicate);

TypedQuery<Notification> query = entityManager.createQuery(cq);
List<Notification> notifications = query.getResultList();


基本上,你可以选择任何一个。如果您更喜欢声明性的方法和简单性,那么推荐使用前两种方法。如果您需要一种动态的编程方法,那么API将是您的选择

ix0qys7i

ix0qys7i2#

假设你有一个这样的角色实体:

@Entity
public class Role {
    private String role;

\\ id and some other fields.

}

字符串
要获取所有在其角色列表中包含特定角色的通知,您只需在JpaRepository中定义一个方法,如下所示:

public interface NotificationRepository extends JpaRepository<Notification, Long> {
    List<Notification> findByRolesRole(String role);
}


并在服务中调用该方法,如下所示:

@Autowired
NotificationRepository notificationRepository;

List<Notification> adminNotifications = notificationRepository.findByRolesRole("admin");

相关问题