Home  >  Spring Core

SqlUpdate Spring JDBC Example

By Arvind Rai, November 09, 2013
In spring JDBC, SqlUpdate is used for reusability of update query. SqlUpdate is a class that needs to be extended by subclass in order to use it. The subclass will define a constructor where we set sql query, sql parameters and then compile() method is called. And finally update() is called to update the row for the given input data. Find the example.

CompanySqlUpdate.java
package com.concretepage;
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;
public class CompanySqlUpdate  extends SqlUpdate {
	public CompanySqlUpdate(DataSource ds) {
        setDataSource(ds);
        setSql("update company set location = ? where id = ?");
        declareParameter(new SqlParameter("location", Types.VARCHAR));
        declareParameter(new SqlParameter("id", Types.NUMERIC));
        compile();
    }
    public int execute(int id, String location) {
        return update(location, id);
    }
}
 
CompanyDao.java
package com.concretepage.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.concretepage.CompanySqlUpdate;
@Repository
public class CompanyDao {
	private CompanySqlUpdate compSqlUpdate;
	@Autowired
	public void setDataSource(DataSource dataSource) {
	    this.compSqlUpdate = new CompanySqlUpdate(dataSource);
	}
	public int updateCompany(int id) {
	    return compSqlUpdate.execute(1, "Bhadohi");
	}
}
 
SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.dao.CompanyDao;
public class SpringTest {
	public static void main(String[] args) {
		ApplicationContext  context = new ClassPathXmlApplicationContext("spring.xml");
		CompanyDao companyDao = (CompanyDao)context.getBean("companyDao");
		int i = companyDao.updateCompany(1);
		System.out.println(i);
	}
}   
 
Table Schema: company
CREATE TABLE `company` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NULL DEFAULT NULL,
	`location` VARCHAR(50) NULL DEFAULT NULL,
	`no_of_emp` INT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
 
Download Source Code for Complete Example
sqlupdate-spring-jdbc-example.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us