1
嗨,大家好我開發了一個彈簧應用程序並卡在一個地方。我正在做的是使用spring rowmapper從數據庫中獲取數據。問題是,在實現rowmapper類時,Model類對象正在創建行數的總數,因此,如果表有10行,則會創建10個模型類對象。 我只想創建該模型類的一個對象,所以我在dao類中注入了模型類,但結果是它僅返回最後一行數據10次。在Spring框架中獲取模型類的單個對象
Model類
public class Item {
private String ItemId;
private String ItemName;
private String price;
// getter & setter
}
DAO類
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;
}
}
主要類
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配置
<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>
而且你會期待什麼呢?如果你有10行的數據庫,你想在列表中只有一個項目?或者更新您的查詢以獲得您期望的單行(distict關鍵字可能會有所幫助,或者對where子句添加一些內容),或者在獲取並映射數據後處理重複項。 – Nadir
我想要完整的行數據。使用第一種方法,即使用新的Item()我得到所有數據,但我希望模型類的Object也創建no。行時間。沒有重複的問題。我只想創建Model類的一個對象。 –
因此,您的模型類應包含不是項目的項目列表,請參閱@Sundararaj Govindasamy答案,應該有所幫助 – Nadir