Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the auto incremented id when performing a second insert in Liquibase?

I am currently playing around with Liquibase and have created a table for users and a table for roles. Each user has a unique id which is auto generated (by a auto increment sequence) when a user is inserted. The roles in the role table are then referencing this id.

Now I try to insert a default user using the Liquibase. First I insert the user and then I want to insert a role which is referring to this newly created user.

The problem is that I can't find a way in Liquibase to retrieve which id was generated for the new user, so that I can use it when inserting the new role.

Is this possible? If it is, how should it be done?

Want to do something like following:

<insert tableName="xxx_user">
    <!-- Id is auto incremented -->
    <column name="user_name" value="XXX" />
    <column name="password" value="XXX" />
    <column name="first_name" value="XXX" />
    <column name="last_name" value="XXX" />
</insert>

<insert tableName="user_role">
    <column name="user_id" value="<point at the auto generated id in previous insert>" />
    <column name="role" value="A_ROLE" />
</insert>
like image 967
eternitysharp Avatar asked Nov 02 '15 09:11

eternitysharp


1 Answers

I use Mysql DB. It is not an elegant solution but works...

    <column name="user_id" valueComputed="(SELECT MAX(id) FROM xxx_user)"/>
like image 153
Juan Miguel Gomez Avatar answered Oct 22 '22 19:10

Juan Miguel Gomez