繁体   English   中英

在 Spring JPA 中执行合并查询

[英]Execute merge query in Spring JPA

我有几个 SQL 表说

table1
___________________________ _ _ _ _ _
|id | date | col1 | col2 |col3 |col4 ...
--------------------------------------
|1  | 1/11 |      |      |     | 
____________________________ _ _ _ _ _

table2
_________________________
|id | date | col1 | col2 |
--------------------------
|1  | 1/11 | ice  | cone |

我希望能够根据 id 和日期将 table2 中的数据合并到 table1 中 - 如果 id 和日期匹配 - 然后将数据(col1 和 col2)从 table2 复制到 table1 上。

我有 SQL 查询来完成这项工作

// merge_query1:

MERGE table1 t1
USING table2 t2
ON (t1.id = t2.id AND t1.date=t2.date )
WHEN MATCHED
    THEN UPDATE SET
                    t1.col1 = t2.col1,
                    t1.col2 = t2.col2
;

现在的问题是如何使用 Spring JPA 执行此操作。

我在想像这样写一个 JPA 接口的东西。

// How would I design this or something like this ? 
// What pojo should be put instead of the question mark in JpaRepository<?, .. >

public interface MergeTables extends JpaRepository<?, Long> {
    @Query(value = MERGE_TABLE2_WITH_TABLE1, nativeQuery = true)
    void executeMergeTableQuery();
}

MERGE_TABLE2_WITH_TABLE1字符串在哪里

public static String MERGE_TABLE2_WITH_TABLE1 = "MERGE table1 t1
                                                   USING table2 t2
                                                   ON (t1.id = t2.id AND t1.date=t2.date )
                                                   WHEN MATCHED
                                                   THEN UPDATE SET
                                                         t1.col1 = t2.col1,
                                                         t1.col2 = t2.col2
                                                   ;
                                                ";

所以问题是我将如何设计以便在调用上述函数时执行合并查询,或者是否有另一种方法来做这样的事情?

添加@Modified@Transactional就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM