我正在尝试进行插入并返回自动生成的 id。这是一个 Oracle 数据库。为此,我正在使用 org.apache.commons.dbutils.QueryRunner insert 它返回第一列。
问题是我不知道出于什么原因我在查询中添加了一个参数,它不会让它工作。
我有这个代码:
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Optional;
@Singleton
public class ConceptToBonusRepository extends GenericSQLRepository{
private static final String QUERY_SAVE_CONCEPT_TO_BONUS = "INSERT INTO concept_to_bonus (ID, CONCEPT_ID, CONCEPT_TYPE)" +
" VALUES (SEQ_CONCEPT_TO_BONUS_ID.NEXTVAL,?,?)";
@Inject
public ConceptToBonusRepository(@Named("OracleDataSource") @Nonnull DataSource dataSource) {
super(dataSource);
}
public Optional<Long> saveConceptToBonus(ConceptToBonus conceptToBonus)
try {
return Optional.ofNullable(
runInsert(
QUERY_SAVE_CONCEPT_TO_BONUS, conceptToBonus.getConceptId(), conceptToBonus.getConceptType()
)
);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
和我的GenericlSQLRepository
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import java.sql.SQLException;
public abstract class GenericSQLRepository {
private QueryRunner queryRunner;
private ScalarHandler<Long> autogeneratedIdHandler = new ScalarHandler<>();
protected GenericSQLRepository(@Nonnull final DataSource dataSource) {
this.queryRunner = new QueryRunner(dataSource);
}
protected Long runInsert(@Nonnull final String sql,
Object... args) throws SQLException {
return queryRunner.insert(sql, this.autogeneratedIdHandler, args);
}
}
当我尝试运行它时,我得到了这个错误
“java.sql.SQLException:错误数量的参数:预期 3,给出了 2 查询:INSERT INTO concept_to_bonus(ID,CONCEPT_ID,CONCEPT_TYPE)VALUES(SEQ_CONCEPT_TO_BONUS_ID.NEXTVAL,?,?)参数:[1731472066,ORDER]”
我真的不明白为什么要在参数计数中添加一个参数。当我通过简单的执行运行此插入时,它工作得很好