Home  >  Spring

queryForInt and queryForObject in Spring JDBC

By Arvind Rai, November 05, 2013
In this page, we learn how to use queryForObject and queryForInt. queryForInt gives the count of rows. queryForObject gives the column value. We can call it with the help of JdbcTemplate. Find the example below.

FarmarDao.java
package com.concretepage.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class FarmarDao {
	private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    public int getCount(){
    	return this.jdbcTemplate.queryForInt("select count(*) from farmar");
    }
    public String getName( int id){
    	return (String) this.jdbcTemplate.queryForObject("select name from farmar where id="+id, String.class);
    }
}
 


SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.dao.FarmarDao;
public class SpringTest {
	public static void main(String[] args) {
		ApplicationContext  context = new ClassPathXmlApplicationContext("spring.xml");
		FarmarDao farmar = (FarmarDao)context.getBean("farmarDao");
		System.out.println(farmar.getCount());
		System.out.println(farmar.getName(2));
	}
}   
 
Download Source Code for Complete Example
queryforint-and-queryforobject-in-spring-jdbc.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us