15
private void insertIntoMyTable (Myclass m) {
    String query = "INSERT INTO MYTABLE (NAME) VALUES (?)";
    jdbcTemplate.update(query, m.getName());
}

当上述查询插入一条记录时,ID表中的列会自动递增。

有没有办法在插入时取回这个自动递增的 ID。所以在这个例子中,我的方法的返回值是int

4

4 回答 4

21

检查此参考。您可以将 jdbcTemplate.update 用作:

编辑 按要求添加了导入

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
于 2012-10-14T14:01:40.210 回答
1

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

  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
    } 
于 2015-05-04T13:00:01.420 回答
1

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 适合您。

于 2018-05-15T14:31:56.813 回答
1
@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);
    }
}
于 2021-02-02T09:24:10.847 回答