在Spring框架中获取模型类的单个对象

时间:2016-10-20 11:47:25

标签: java spring spring-jdbc spring-bean

大家好我开发一个弹簧应用程序并卡在一个地方。我正在做的是使用spring rowmapper从数据库中获取数据。问题是在实现rowmapper类时,Model类对象正在精确地创建总行数,因此,如果表有10行,则创建10个模型类对象。 我想只创建该模型类的一个对象,所以我在dao类中注入了模型类,但结果是它只返回最后一行数据10次。

模型类

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>

1 个答案:

答案 0 :(得分:2)

使用 queryForObject ()代替query(),查看所有可用API的JDBCTemplate类的java文档。

参考示例

<div class="controllers">
  <span id='one' class='active'>Lorem</span>
  <span id='two'>Lorem</span>
  <span id='three'>Lorem</span>
</div>