Hi guys I developing a spring application and got stuck in one place. What I am doing is fetching the data from the database using spring rowmapper. The problem is while implementing the rowmapper class Model class object is creating exactly the total number of rows times so, if table has 10 rows then 10 object of model class is created. I want to create only one object of that model class so I injected the model class in the dao class but the result is it returning the last row data only 10 times.
Model class
public class Item {
private String ItemId;
private String ItemName;
private String price;
// getter & setter
}
DAO class
public class Itemdao {
private JdbcTemplate template;
private Item items;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Item> getItem(){
return template.query("select * from item", new RowMapper<Item>(){
@Override
public Item mapRow(ResultSet rs, int rownum) throws SQLException
{
//Item item = new Item(); // Using this line I get 10 objects of model
items.setItemId(rs.getString(1));
items.setItemName(rs.getString(2));
items.setPrice(rs.getString(3));
return items;
}});
}
public Item getItems() {
return items;
}
public void setItems(Item items) {
this.items = items;
}
}
Main class
public class test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spconfig.xml");
Itemdao dItemdao = (Itemdao)context.getBean("item");
List<Item> list = dItemdao.getItem();
for(Item i:list)
System.out.println(i);
}
}
Spring configuration
<beans>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="sandhya" />
<property name="password" value="2611798" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
<bean id="items" class="com.shopping.Item.Model.Item"/>
<bean id="item" class="com.shopping.Item.Model.Itemdao">
<property name="template" ref="jdbcTemplate"/>
<property name="items" ref="items"/>
</bean>
</beans>