Intro jdbc project

For using SpringJDBC, we have two class
a) JdbcTemplate
b)DriverManagerDataSource

In DriverManagerDataSource, we have to give the property of url, drivername, username and password and create a bean with it.

We inject the bean of DriverManagerDataSource to JdbcTemplate.
We have all the method in JbbcTemplate for creating, inserting  deleting in database.

update() -> is used for insert, update, delete
execute() -> select

It is inserted like this:
String query = "insert into student(name, address) values (?,?)";
int result = jdbcTemplate.update(query, s.getName(), s.getAddress());
Updating and deleting is same as inserting but with different query.
public int update(Student s) {
String query = "UPDATE student SET name=?, address=? WHERE id=?";
int result = jdbcTemplate.update(query, s.getName(), s.getAddress(), s.getId());
return result;
}

public int delete(int studentId) {
String query = "DELETE FROM student WHERE id=?";
int result = jdbcTemplate.update(query, studentId);
return result;
}

For getting the object from database
For single query: jdbcTemplate.queryForObject(String query, RowMapper rowMapper, Object args);
For all:  jdbcTemplate.queryForObject(String query, RowMapper rowMapper);
public Student getStudent(int studentId) {
String query = "SELECT * FROM student WHERE id=?";
RowMapper<Student> rowMapper = new RowMapperImpl();
Student student = jdbcTemplate.queryForObject(query, rowMapper, studentId);
return student;
}

public List<Student> getAllStudents() {
String query = "SELECT * FROM student";
RowMapper<Student> rowMapper = new RowMapperImpl();
List<Student> studentList = jdbcTemplate.query(query, rowMapper);
return studentList;
}

Own RowMapper<T> should be implemented and make object.

public class RowMapperImpl implements RowMapper<Student> {

public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setAddress(resultSet.getString(3));
return student;
}
}

Comments

Popular posts from this blog