在 JBoss 下链 MySQL 个语句

Chain MySQL statements under JBoss

编辑:链接的答案未使用 LAST_INSERT_ID,仍在寻找答案。

我正在使用 JBoss 并通过数据源 (JNDI) 获取连接。

如何一次链接并执行多个 SQL 语句,其中第二个语句取决于第一个 (LAST_INSERT_ID())

的输出
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);
        }
    }
};

请注意:我也生成了正在使用的密钥,第二个 table 没有生成任何密钥,因为它是一个连接 table。

  1. 配置JBoss以允许在管理界面中进行多个查询。在添加属性之前先单击禁用。 (在数据源下)。

    属性名称:allowMultiQueries 属性 值:true

  2. 生成的键不会有问题,因为第二个查询没有自动递增主键。