我正在将Spring JDBC模板与Oracle数据库一起使用。 我希望在成功插入数据库后返回自动生成的ID字段。
请帮我从DB
获取自动生成的ID以下是我的示例代码:
public class EmployeeObject {
int employeeId;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
- DAO界面 -
public interface CreateEmployeeDao {
public void insertIntoEmployeeObject(EmployeeObject employeeObject);
}
- DAO IMPL -
public class CreateEmployeeDaoImpl implements CreateEmployeeDao{
@Override
public void insertIntoEmployeeObject(EmployeeObject employeeObject){
String sqlInsertObject = CreateEmployeeDBQueryConstants.INSERT_OBJECT_DETAILS.toString();
int record = getJdbcTemplate().update(sqlInsertObject,
new Object[] { employeeObject.getEmployeeId(),
employeeObject.getFirstName(),
employeeObject.getLastName()});
}
}
DB QUERY CONSTRANT
public class CreateEmployeeDBQueryConstants {
public static final StringBuffer INSERT_OBJECT_DETAILS = new StringBuffer(100);
static{
INSERT_OBJECT_DETAILS.append("insert into EXPORT_OBJECT "
+ "(EMPLOYEE_ID,EMPLOYEE_FIRST_NAME,EMPLOYEE_LAST_NAME, "
+ " values (?,?,?)");
}
}
答案 0 :(得分:1)
使用@Darshan提到的GeneratedKeyHolder
是要走的路。
我更喜欢使用http://alvinalexander.com/blog/post/jdbc/spring-jdbc-insert-auto-generated-key:
中显示的方法KeyHolder keyHolder = new GeneratedKeyHolder();
getNamedParameterJdbcTemplate().update(sqlString, parameters, keyHolder);
return keyHolder.getKey().intValue();
答案 1 :(得分:0)
您需要使用update
方法的重载版本,该方法将PreparedStatementCreator
和KeyGenerator
作为参数(记录为here):
您的代码如下所示:
KeyHolder holder = new GeneratedKeyHolder();
PreparedStatementCreator creator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement insertStatement = con.prepareStatement(INSERT_OBJECT_DETAILS, new Object[] {
employeeObject.getEmployeeId(),
employeeObject.getFirstName(),
employeeObject.getLastName()}));
return insertStatement;
}
};
getJdbcTemplate().update(creator, holder);
System.out.println(holder.getKey());