JPA/Spring对非托管联接表的查询
我想知道使用JPA、Spring存储库或两者的组合是否可以实现以下功能 假设我拥有以下JPA托管实体:JPA/Spring对非托管联接表的查询,spring,jpa,Spring,Jpa,我想知道使用JPA、Spring存储库或两者的组合是否可以实现以下功能 假设我拥有以下JPA托管实体: +------------+ |notification| +------------+ |id | |message | |isClosable | +------------+ 现在假设我有一个不由JPA管理的简单联接表: +------------------+ |user_notifications| +------------------+ |id
+------------+
|notification|
+------------+
|id |
|message |
|isClosable |
+------------+
现在假设我有一个不由JPA管理的简单联接表:
+------------------+
|user_notifications|
+------------------+
|id |
|userName |
|notificationId |
+------------------+
我想知道这样的事情是否可能:
@Query("FROM Notification n where n.id IN (select notificationId from user_notifications where userName = :user)")
getNotificationsForUser(String user);
同样,通知
是一个托管的@实体
,但用户通知不是。我必须创建相应的@Entity
类才能执行此操作
+加分+
我希望单个用户关闭通知,但我同样不确定如何使用JPA与非托管表交互
因此,我希望有一个类似于以下内容的spring存储库方法:
@Query("DELETE from user_notifications where notificationId = :noteId AND userName = :user")
closeNotificationForUser(Long noteId, String user);
非常感谢你的帮助 根据@JB_Nizet的评论,我研究了如何将SQL与Spring存储库结合使用,发现Spring的
@Query
注释具有nativeQuery
布尔属性
我能够实现如下选择方法:
@Query(value = "SELECT * FROM notification WHERE id IN (SELECT notificationId FROM user_notifications WHERE userName = :user)", nativeQuery = true)
public List<Notification> findByUser(@Param(value = "user") String user);
JPQL使用实体、它们的字段和关联。从不使用表名和列名。如果需要查询未映射的表,请映射它们,或者使用SQL.JPQL查询也可以启动选择、删除或更新。其他任何内容都是非标准的特定于供应商的,不值得使用
// Required
@Transactional
public void closeNotification(Long notificationId, String user) {
// note createNativeQuery
Query query = entityManger
.createNativeQuery("DELETE FROM user_notifications WHERE userName = :user AND notificationId = :notificationId");
query.setParameter("notificationId", notificationId);
query.setParameter("user", user);
// executeUpdate(), not execute()
query.executeUpdate();
}