Say I have three tables: team, player, team_player. The team_player table is a bridge table that allows you to use many-many relationships.
When someone wants to create a new team, they indicate the initial players in this team.
How to insert both a team and team_player commands into a single transaction? That is, I would like to insert all the team_player entries before moving on to the new team. I use JDBC and Oracle.
When I try to execute the code below, teamId is populated with a string of letters, although team.id is a number (which is incremented with a trigger). So this is not like the id of the record I was just trying to insert (but not committed yet).
c = DB.getConnection(); c.setAutoCommit(false); sql = "INSERT INTO team (name) values (?)"; myInsert = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); myInsert.setString(1, "cougars"); int affectedRows = memoInsert.executeUpdate(); String teamId; ResultSet generatedKeys = myInsert.getGeneratedKeys(); if (generatedKeys.next()) { teamId = generatedKeys.getString(1); } // ...loop through players inserting each player and team.id into team_player // c.commit();
Here I read about RETURN_GENERATED_KEYS: How to get the insert ID in JDBC?
source share