【问题标题】:I am new to springboot and need to insert json data in oracle table and avoid duplicate inserts我是springboot新手,需要在oracle表中插入json数据,避免重复插入
【发布时间】:2021-04-27 16:10:51
【问题描述】:

我可以使用 springboot 的中间表在 oracle 表中插入 json 数据

我有一张桌子 abc-

ID  first_name  last_name  cust_ID  Active_Ind last_upd_dt
1   abc         pqr          101     Y          01-Apr-2021
2   aaa         bbb          102     Y          05-Feb-2021

我需要确保—— 如果新的 json 数据具有上述现有值,则不要更新表 abc,保持原样,如果有新记录,则插入。如果新的 json 数据中不存在 oracle 表记录,则将 ACTIVE_IND 更改为 'N'

我尝试使用以下查询插入中间表“test”中不存在的值:

insert into abc
(ID, 
first_name, 
last_name, 
cust_ID, 
active_ind, 
last_upd_dt)
select 
abc_seq.nextval,
first_name, 
last_name, 
cust_ID, 
active_ind, 
last_upd_dt 
from test t
where not exists(
select null from abc a
where a.fist_name = t.first_name
and a.cust_ID = t.cust_ID);

这在 Oracle 开发人员中运行良好,但是当我在 springboot 中尝试以下查询时,它以某种方式插入重复项,不知道为什么会发生这种情况,我已经为索引使用了准备好的语句。

insert into abc
(ID, 
first_name, 
last_name, 
cust_ID, 
active_ind, 
last_upd_dt)
select 
abc_seq.nextval,
?, 
?, 
?, 
?, 
?
from test t
where not exists(
select null from abc a
where a.fist_name = t.first_name
and a.cust_ID = t.cust_ID);```

I have tried merge queries as well, but none of them worked for me.

【问题讨论】:

    标签: java sql json oracle spring-boot


    【解决方案1】:

    如果您使用的是 Spring Boot,我假设您已经映射了实体并且您正在使用 JPA。

    一旦你映射了实体

    @Entity
    @Table(name = "abc")
    public class ABC {
    
       @Id
       private Long id;
       
       @Column(name = "name")
       private String name;
       
       ...
    }
    

    然后我还假设您创建了一个存储库(如果您使用的是 Repo 模式)

    public interface ABCRepository extends JpaRepository<ABC, Long> {
    
       //leave it blank If you don't need any particular method for querying
    }
    

    在这种情况下,您可以使用 findOne JPA 方法传递您希望结果匹配的对象的示例。如果只是 ID,则只需使用 findByID。无论如何,您现在可以自己创建一个 saveIfExists(示例)

    public ABC saveIfNotExists(Example<ABC> example) {
       return abcRepo.findOne(example).orElse(()-> {
         return abcRepo.save(example);
       };
    }
    

    【讨论】:

    • 感谢您的回复,我正在为此使用 JdbcItemReader 和 Writer。我使用了ignore_row_on_dupkey_index,并且很好地忽略了重复项。最初它给出了违反唯一约束的错误,但这解决了。感谢您的宝贵时间
    • 很高兴你找到了自己的出路!
    猜你喜欢
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多