使用 liquibase 将数据加载到 postgres 关系表中

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

我在 postgres 中有 2 个关系表,使用 liquibase,我需要为每两个表插入 csv 文件中的数据,而不需要对任何 id 列进行硬编码。我的架构看起来像

table1(
  id numeric,
  filed1 varchar,
  field2 varchar
)
table2(
  id numeric,
  table1_id numeric references table1.id,
  field3 varchar
)

id 列是数字,每个表都有自己的序列生成器,我无法从 csv 文件中引用它,也无法在表创建中设置默认值,因此我需要将每个表数据插入到临时表中,然后将其移动到实际的表中。桌子与

<sql>insert into table1 (id,field1,field2)
    select nextval('table1_sequence'), field1, field2 from table1_temp
</sql

我面临的挑战是当我插入table2时,如何引用父表?意思是如何将table1的id放入table2.table1_id中?

postgresql spring-boot hibernate csv liquibase
1个回答
0
投票

这是下面所示的

solution way

1 )

XML
table
的格式如下所示

<changeSet id="1" author="yourname">
    <!-- Create main tables -->
    <createTable tableName="table1">
        <column name="id" type="numeric" />
        <column name="field1" type="varchar(255)" />
        <column name="field2" type="varchar(255)" />
    </createTable>

    <createTable tableName="table2">
        <column name="id" type="numeric" />
        <column name="table1_id" type="numeric" />
        <column name="field3" type="varchar(255)" />
        <constraints foreignKeyName="fk_table2_table1" referencedTableName="table1" referencedColumnNames="id"/>
    </createTable>

    <!-- Create sequences for ID generation -->
    <createSequence sequenceName="table1_sequence"/>
    <createSequence sequenceName="table2_sequence"/>
</changeSet>

2) 这是下面所示的

insert
示例

<changeSet id="3" author="yourname">
    <!-- Mapping table to track generated IDs in table1 -->
    <createTable tableName="table1_mapping">
        <column name="temp_field1" type="varchar(255)" />
        <column name="new_id" type="numeric" />
    </createTable>

    <!-- Insert into table1 and store generated IDs in table1_mapping -->
    <sql>
        INSERT INTO table1 (id, field1, field2)
        SELECT nextval('table1_sequence'), field1, field2
        FROM table1_temp
        RETURNING field1, id INTO table1_mapping (temp_field1, new_id);
    </sql>
</changeSet>

<changeSet id="4" author="yourname">
    <!-- Insert into table2 using IDs from table1_mapping -->
    <sql>
        INSERT INTO table2 (id, table1_id, field3)
        SELECT nextval('table2_sequence'), mapping.new_id, temp.field3
        FROM table2_temp temp
        JOIN table1_mapping mapping
        ON temp.table1_field1 = mapping.temp_field1;
    </sql>
</changeSet>
© www.soinside.com 2019 - 2024. All rights reserved.