使用JDBC使用外键批量插入多个表中

问题描述 投票:0回答:1

我正在编写一个接收树结构并将其插入数据库的方法,其中每个分支都是另一个数据库表。例如:

tree = {
    "_id": "111",
    "field1": "",
    "field2": "",
    "field3": {
        "_id": "333",
        "_parent_id": "111",
        "field3_1": "",
        "field3_2": "",
        "field3_3": [
            {
                "_id": "1",
                "_parent_id": "333",
                "field3_3_1": ""
            },
            {
                "_id": "2",
                "_parent_id": "333",
                "field3_3_1": ""
            },
            {
                "_id": "3",
                "_parent_id": "333",
                "field3_3_1": ""
            }
        ]
    }
}

应对应于3个表:tree,field3和field3_3-在_id和_parent_id上具有关系。每个分支可以是单个值,表或对象,基本上树是与PostgreSQL数据库中某些数据结构相对应的动态结构。我正在使用jdbc将数据插入数据库。当用户可能会提供具有多个分支或多个分支值的大树时,插入此类数据的最佳方法是什么?我在考虑这样的声明:

                 with first_insert as(
                 insert into sample(firstname, lastname)
                 values('fai55', 'shaggk')
                 RETURNING id
                 ),

                 second_insert as(
                 insert into sample1(id, adddetails)
                 values
                 ((select id from first_insert), 'ss')
                 RETURNING user_id
                 )

但是如果内部插入应该在大批记录上起作用(field3_3将为每个数据行包含100k条记录,就会出现问题。

我已经使用PreparedStatement和executeBatch()在单个数据库级别上实现了接受表和插入的方法,并且效果很好。像这种方法一样,可用于树木吗?

java jdbc insert batch-processing relation
1个回答
0
投票

如果树是动态结构,我认为您将必须将收到的json解析为可以在Java中工作的东西。

可以使用和JSONObject实现。假设您在String data中序列化了传入的json。然后您可以使用:

JSONObject dataJson = new JSONObject(data);

现在您可以在Java中使用此树结构。您可以使用dataJson.toString()将其序列化回来,也可以创建自定义序列化器。

如果问题是插入大小,则可以遍历dataJson并将其分成合理的块。例如,您可以使用类似这样的内容

        JSONArray jsonArr = dataJson.getJSONArray("field3");
        JSONArray dataAccumJsonArr = new JSONArray();
        for (int i = 0; i < jsonArr.length(); i++) {
            dataAccumJsonArr.put(jsonArr.get(i));
            if (dataAccum.length() > 999) {
                doInsert(dataAccumJsonArr);
                dataAccumJsonArr = new JSONArray();
            }
        }
        doInsert(dataAccumJsonArr);
© www.soinside.com 2019 - 2024. All rights reserved.