Reputation: 45
I tried to add multiple datum to relatives table using jdbcTemplate.batchUpdate
:
I tried to select the maxid
from student table and have used in insert query as the id.
This is my code:
List<Relatives> relatives=student.getRelatives();
String sql3="Select Id,Name from Student where Id=(select Max(Id) from student)";
final Student student1= (Student) jdbcTemplate.query(sql3, new UserMapper5());
String sql4 = " INSERT INTO Relatives (StudentId,RelativeId,YearId,ClassId,SectionId,RelationshipId,IsDeleted,CreatedBy,CreatedDate) "+
" Values(?,?,?,?,?,?,?,?,GETDATE())";
int[][] updateCounts = jdbcTemplate.batchUpdate(sql4, relatives, relatives.size(),
new ParameterizedPreparedStatementSetter<Relatives>() {
public void setValues(PreparedStatement ps, Relatives relative) throws SQLException {
ps.setInt(1, student1.getId());
ps.setString(2, relative.getStudent().getName());
ps.setInt(3, relative.getStudent().getYear().getId());
ps.setInt(4, relative.getStudent().getClasss().getId());
ps.setInt(5, relative.getStudent().getSection().getId());
ps.setInt(6, relative.getRelationship().getId());
ps.setInt(7, 0);
ps.setInt(8,123);
}
}
);
I'm getting the below error When I tried to insert multiple data to relatives table:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.cloudnexus.spring.model.Student
Upvotes: 2
Views: 319
Reputation: 4064
Use jdbcTemplate.queryForObject
instead which can return Object what you expect. Current method you are using returns List which is not you are expecting(as per the sql query
it should return only one record).
Upvotes: 1
Reputation: 2665
This will solve your problem:
final Student student1= (Student) jdbcTemplate.queryForObject(sql3, new UserMapper5());
Also you can make your UserMapper5
a generic one and avoid casting:
public class UserMapper5<T> implements RowMapper {
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
/// ...
}
}
And then:
final Student student1= jdbcTemplate.queryForObject(sql3, new UserMapper5<Student>());
Upvotes: 0
Reputation: 58772
jdbcTemplate.query with RowMapper
returns a List, and then if not empty get the student:
List<Student> studentList = jdbcTemplate.query(...
if (!studentList.isEmpty()){
Student student1 = studentList.get(0);
Returns: the result List, containing mapped objects
Upvotes: 2