title: Chain MySQL statements under JBoss
body: <p>EDIT: the linked answer doesn't use <code>LAST_INSERT_ID</code>, still looking for answer.</p>
  
  <p>I'm using JBoss and getting connections via DataSource (JNDI).</p>
  
  <p>How can I chain and execute multiple SQL statements in one go, where the second statement depends on the output of the first (<code>LAST_INSERT_ID()</code>)</p>
  
  <pre><code>preparedStatement = connection.prepareStatement("INSERT INTO product(name) VALUES(?); INSERT INTO brand_product(brand_id, product_id) VALUES(?, LAST_INSERT_ID())", Statement.RETURN_GENERATED_KEYS);
  preparedStatement.setString(1, name);
  preparedStatement.setInt(2, brandId);
  
  if(preparedStatement.executeUpdate() != 0) {
      try (ResultSet generatedKeys = preparedStatement.getGeneratedKeys()) {
          if(generatedKeys.next()) {
              product = new Product(generatedKeys.getInt(1), name);
          }
      }
  };
  </code></pre>
  
  <p>Please note: I've generated keys in use as well, the second table is not generating any keys since it's a join table. </p>