Spring: RowMapper Example
RowMapper Example
Create Following files in java project in eclipse.
Database name: test
Table : employee (id, name, salary)
You need spring jar files and MySql Driver file.
1. Employee.java
Property: id, name, salary
Create constructor, getters, setters and toString.
2. EmployeeDao.java
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Employee> getAllEmployeesRowMapper() {
return jdbcTemplate.query("select * from employee",
new RowMapper<Employee>() {
@Override
public Employee mapRow(ResultSet rs, int rownumber)
throws SQLException {
// TODO Auto-generated method stub
Employee e = new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
return e;
}
});
}
}
3. TestMain.java
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"myBean.xml");
EmployeeDao dao = (EmployeeDao) ctx.getBean("edao");
List<Employee> list=dao.getAllEmployeesRowMapper();
for (Employee e : list)
System.out.println(e);
}
4. myBean.xml
Create 3 beans ds, jdbcTemplate and edao.
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.smgc.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
Comments
Post a Comment