非托管连接表上的JPA / Spring查询

时间:2015-11-02 03:07:08

标签: spring jpa

我想知道使用JPA,Spring Repositories还是两者的结合是否可以实现以下目标。

假设我有以下JPA管理实体:

+------------+
|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);

同样,Notification是托管@Entity,但user_notifications不是。我是否必须创建相应的@Entity类来执行此操作。

+ BONUS POINTS +

我希望个别用户关闭通知,但我不知道如何使用JPA与非托管表进行交互。

所以我希望有一个类似于:

的spring存储库方法
@Query("DELETE from user_notifications where notificationId = :noteId AND userName = :user")
closeNotificationForUser(Long noteId, String user);

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

Per @ JB_Nizet的评论,我研究了在Spring Repository中使用SQL,发现Spring的@Query注释有一个nativeQuery布尔属性。

我能够按如下方式实现select方法:

@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);

从未映射的连接表中删除条目需要创建custom repository method,其实现如下所示:

// 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();
}
相关问题