java 当我通过jdbctemplate在表中插入记录时,如何获得自动递增的id

lymgl2op  于 2023-03-11  发布在  Java
关注(0)|答案(4)|浏览(221)
private void insertIntoMyTable (Myclass m) {
    String query = "INSERT INTO MYTABLE (NAME) VALUES (?)";
    jdbcTemplate.update(query, m.getName());
}

当上述查询插入记录时,表中的ID列自动递增。
有没有办法在插入的时候把这个自动递增的ID取回来,所以在这个例子中,我的方法的返回值是int

dly7yett

dly7yett1#

查看Chapter 11. Data access using JDBC参考。您可以使用jdbcTemplate.update作为:

EDIT已按要求添加导入

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

以下是代码用法:

final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
    new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps =
                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
            ps.setString(1, name);
            return ps;
        }
    },
    keyHolder);
// keyHolder.getKey() now contains the generated key
bttbmeg0

bttbmeg02#

我得到的ID生成的数据库(MSSQL)后插入如下,导入:

import org.springframework.jdbc.core.BeanPropertyRowMapper;
  import org.springframework.jdbc.core.JdbcTemplate;
  import org.springframework.jdbc.core.RowMapper;
  import org.springframework.jdbc.core.SqlParameter;
  import org.springframework.jdbc.core.SqlReturnResultSet;
  import org.springframework.jdbc.core.simple.SimpleJdbcCall;

和代码片段:

final String INSERT_SQL = "INSERT INTO [table]\n"
            + " ([column_1]\n"
            + " ,[column_2])\n"
            + " VALUES\n" +
            " (?, ?)";

    Connection connection = jdbcTemplate.getDataSource().getConnection();
    PreparedStatement preparedStatement = connection.prepareStatement(INSERT_INVOICE_SQL, Statement.RETURN_GENERATED_KEYS);
    preparedStatement.setString(1, "test 1");
    preparedStatement.setString(2, "test 2");

    preparedStatement.executeUpdate();
    ResultSet keys = preparedStatement.getGeneratedKeys();

    if (keys.next()) {
        Integer generatedId = keys.getInt(1); //id returned after insert execution
    }
piwo6bdm

piwo6bdm3#

JdbcTemplate是Spring的核心,另一个选择是使用SimpleJdbcInsert

SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
simpleJdbcInsert
    .withTableName("TABLENAME")
    .usingGeneratedKeyColumns("ID");
SqlParameterSource params = new MapSqlParameterSource()
    .addValue("COL1", model.getCol1())
    .addValue("COL2", model.getCol2());
Number number = simpleJdbcInsert.executeAndReturnKey(params);

您仍然可以@Autowire jdbcTemplate,对我来说,这比使用jdbcTemplate.update()方法和KeyHolder获取实际的id更方便。
示例代码片段使用Apache Derby进行了测试,应该可以与常用数据库一起使用。
使用Spring JPA是另一种选择-如果ORM适合您的话。

tcbh2hod

tcbh2hod4#

@Component
public class PersonDao {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public PersonDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Person> index() {
        return jdbcTemplate.query("SELECT * FROM person", new BeanPropertyRowMapper<>(Person.class));
    }

    public Person show(int id){
        return jdbcTemplate.query("SELECT * FROM person WHERE id=?", new Object[]{id}, new BeanPropertyRowMapper<>(Person.class))
                .stream().findAny().orElse(null);
    }

    public void save(Person person){
        jdbcTemplate.update("INSERT INTO person (name, age, email) VALUES (?, ?, ?)", person.getName(), person.getAge(), person.getEmail());
    }

    public void edit(Integer id, Person person) {
        jdbcTemplate.update("UPDATE person SET name = ?, age = ?, email = ? WHERE id = ?", person.getName(), person.getAge(), person.getEmail(), id);
    }

    public void delete(Integer id) {
        jdbcTemplate.update("DELETE FROM person WHERE id = ?", id);
    }
}

相关问题