在Oracle上合并查询但不更新查询

时间:2019-01-29 10:37:05

标签: sql oracle oracle11g spring-data-jpa

我在Spring的 @SQLInsert 批注中针对Oracle 11g数据库获得了此查询,尽管它正确插入,但它不会更新值,但不会出错。

有什么想法吗?如果不是,是否有其他方法可以获取相同的行为?

merge INTO ngram sn
USING(SELECT ? AS frequency,
             ? AS occurrences,
             ? AS ngram
      FROM   dual) src
ON (sn.ngram = src.ngram)
WHEN matched THEN
  UPDATE SET sn.occurrences = sn.occurrences + src.occurrences,
             sn.frequency = sn.frequency + 1
WHEN NOT matched THEN
  INSERT (ngram,
          frequency,
          occurrences)
  VALUES (src.ngram,
          src.frequency,
          src.occurrences) 

Update1:​​:为了澄清起见,我在Java中添加了Entity def。

@Entity(name = "NGRAM")
public class Ngram
{
    @Id
    @JsonProperty("ngram")
    private String ngram;

    @JsonProperty("frequency")
    @Column(name = "frequency")
    private int frequency;

    @JsonProperty("occurrences")
    @Column(name = "occurrences")
    private int occurrences;

Update2::在现有Ngram上添加SQL查询的运行

sql> merge INTO NGRAM sn
     USING(SELECT 1 AS frequency,
                  200 AS occurrences,
                  'year' AS ngram
           FROM   dual) src
     ON (sn.ngram = src.ngram)
     WHEN matched THEN
       UPDATE SET sn.occurrences = sn.occurrences + src.occurrences,
                  sn.frequency = sn.frequency + 1
     WHEN NOT matched THEN
       INSERT (ngram,
               frequency,
               occurrences)
       VALUES (src.ngram,
               src.frequency,
               src.occurrences)
[2019-01-29 12:09:10] 1 row affected in 19 ms

这实际上修改了行,但是当我在代码中遍历它们时却没有,所以看起来SQL是正确的...

Update3:因此,这是应该插入或更新的代码段,但它只执行插入操作:

    List<Ngram> lNgrams = new ArrayList<>(lCollocationsMap.size());
    lCollocationsMap.forEach((pKey, pValue) -> lNgrams.add( new Ngram(pKey, 1, pValue)));
    mNgramRepo.saveAll(lNgrams);

所以我将调查 saveAll 行为。

Update4::我尝试一次使用 save ,这比使用 saveAll 慢得多,但是行为却相同。将 ON(sn.ngram = src.ngram)更改为 ON(sn.ngram像src.ngram)会使某些频率变为2(因此它们似乎是已更新),但并非全部:例如,“年”出现了10次以上,但它的频率保持为1,并且它的出现只是用找到的最后一个值进行了更新。

因此,我现在完全迷失了失败的原因,特别是这种方式。

0 个答案:

没有答案