如何使用JDBC从List(嵌套)插入数据库

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

我有3个不同的表,我想在其中插入以JSON形式出现的数据。以下是我的数据结构。

流类:

public class StreamsID {
    private Long id;
    private Long campaign_id;
    private Long credential_id;
    private String user_id;
    private String custom_name;
    private List<Item> items;
}

物品类:

public class Item {
    private Long stream_id;
    private String stream_item_date;
    private String channel;
    private List<Workflow> workflow;
    private List<Responses> responses;

工作流程类:

public class Workflow {
    public static final String FIND_ALL = "findAll";
    private Long id;
    private User actor;
    private User assignee;
    private String date;
    private String team;
    private String action;

我正在使用PreparedStatement插入数据:

PreparedStatement statement = connection.prepareStatement("INSERT INTO public.streams(" +
                        "stream_id, stream_campaign_id," +
                        "stream_user_id, stream_custom_name) " +
                        "VALUES (?, ?, ?, ?);");
        statement.setLong(1,stream.getId());
        statement.setLong(2,stream.getCampaign_id());
        statement.setLong(3,stream.getCredential_id());
        statement.setString(4,stream.getUser_id());
        statement.setString(5,stream.getCustom_name());

这种方法的问题是我无法保存项目和工作流程表。我不确定如何在JDBC中实现它。我们使用的数据库是Postgresql。

当我使用JPA时,这要容易得多,但我们必须切换到JDBC以获得一些约束。任何帮助都非常感谢。

java postgresql jdbc
1个回答
3
投票

要在JDBC上插入List,您需要使用循环,并调用addBatch()。 对于Item(假设有一个名为StreamsIDstream),它应该是这样的:

PreparedStatement statement = connection.prepareStatement("INSERT INTO item(stream_id,"+
                                          "stream_item_date, channel) "+
                                          "VALUES (?, ?, ?);");
for(Item item : stream.getItems()){
    statement.setLong(1, item.getStream_id());
    statement.setString(2, item.getStream_item_date());
    statement.setString(3, item.getChannel());
    statement.addBatch();
}
© www.soinside.com 2019 - 2024. All rights reserved.