91-9990449935 0120-4256464 |
RowMapper Example | Fetching records by Spring JdbcTemplateLike ResultSetExtractor, we can use RowMapper interface to fetch the records from the database using query() method of JdbcTemplate class. In the execute of we need to pass the instance of RowMapper now. Syntax of query method using RowMapperRowMapper InterfaceRowMapper interface allows to map a row of the relations with the instance of user-defined class. It iterates the ResultSet internally and adds it into the collection. So we don't need to write a lot of code to fetch the records as ResultSetExtractor. Advantage of RowMapper over ResultSetExtractorRowMapper saves a lot of code becuase it internally adds the data of ResultSet into the collection. Method of RowMapper interfaceIt defines only one method mapRow that accepts ResultSet instance and int as the parameter list. Syntax of the method is given below: Example of RowMapper Interface to show all the records of the tableWe are assuming that you have created the following table inside the Oracle10g database. Employee.javaThis class contains 3 properties with constructors and setter and getters and one extra method toString(). EmployeeDao.javaIt contains on property jdbcTemplate and one method getAllEmployeesRowMapper. applicationContext.xmlThe DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection URL, username and password. There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property. Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can use constructor also. Test.javaThis class gets the bean from the applicationContext.xml file and calls the getAllEmployeesRowMapper() method of EmployeeDao class.
download this example (developed using MyEclipse IDE)
download this example (developed using Eclipse IDE) |