Monday, November 6, 2017

Spring JDBC - Program to connect Database using jdbcTemplate

Spring jdbc is very important as all the enterprise level application always use database and Spring JDBC comes in picture when we connect database with java application using spring framework.


Below  program we are using the spring jdbcTemplate along with Java.

The structure of the project would be like below


Database we are using is MYSQL.


Below is the Program

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource"
abstract="false" autowire-candidate="true">
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver.classname}"></property>
<property name="url" value="${jdbc.url}"></property>
</bean>
<!-- <bean id="orgDao"
class="com.vp.springdemo.dao.impl.OrganizationDaoImpl">
<property name="dataSource" ref="ds"></property>
</bean> -->
<context:property-placeholder location="organization.properties" />
<context:component-scan base-package="com.vp.springdemo"></context:component-scan>
</beans>
view raw bean-cp.xml hosted with ❤ by GitHub
package com.vp.springdemo;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.BadSqlGrammarException;
import com.vp.springdemo.dao.OrganizationDao;
import com.vp.springdemo.dao.impl.OrganizationDaoImpl;
import com.vp.springdemo.domain.Organization;
public class JDBCDemoApp {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-cp.xml");
OrganizationDao orgDao = (OrganizationDaoImpl) ctx.getBean("orgDao");
List<Organization> orgList =null;
try {
orgList=orgDao.getAllOrganization();
for(Organization org :orgList) {
System.out.println(org);
}
}catch(BadSqlGrammarException ex) {
System.err.println("Bad error"+ex.getLocalizedMessage());
}
catch(DataAccessException ex) {
System.out.println(ex.getMessage());
}
}
}
package com.vp.springdemo.domain;
public class Organization {
private String slogan;
private int totalEmployee;
private int yearOfIncorporation;
private String name;
private String address;
private int id;
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public void setTotalEmployee(int totalEmployee) {
this.totalEmployee = totalEmployee;
}
public void setYearOfIncorporation(int yearOfIncorporation) {
this.yearOfIncorporation = yearOfIncorporation;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Organization [slogan=" + slogan + ", totalEmployee=" + totalEmployee + ", yearOfIncorporation="
+ yearOfIncorporation + ", name=" + name + ", address=" + address + "]";
}
public void setId(int int1) {
// TODO Auto-generated method stub
this.id = int1;
}
public int getId() {
return this.id;
}
}
jdbc.url = jdbc:mysql://127.0.0.1/springlearning
jdbc.password = root
jdbc.username = root
jdbc.driver.classname = com.mysql.jdbc.Driver
package com.vp.springdemo.dao;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import com.vp.springdemo.domain.Organization;
public interface OrganizationDao {
public void setDataSource(DataSource datasource);
// method to get all the organization
public List<Organization> getAllOrganization();
public boolean createOrganization(Organization org);
public int updateOrganization();
public boolean deleteOrganication(int id);
}
package com.vp.springdemo.dao.impl;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.vp.springdemo.dao.OrganizationDao;
import com.vp.springdemo.domain.Organization;
import com.vp.springdemo.util.OrganizationRowMapper;
@Repository("orgDao")
public class OrganizationDaoImpl implements OrganizationDao {
JdbcTemplate jdbcTemplate =null;
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Organization> getAllOrganization() {
// TODO Auto-generated method stub
String querystr ="select * from Organization";
return jdbcTemplate.query(querystr,new OrganizationRowMapper());
}
public boolean createOrganization(Organization org) {
// TODO Auto-generated method stub
return false;
}
public int updateOrganization() {
// TODO Auto-generated method stub
return 0;
}
public boolean deleteOrganication(int id) {
// TODO Auto-generated method stub
return false;
}
}
package com.vp.springdemo.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import com.vp.springdemo.domain.Organization;
public class OrganizationRowMapper implements RowMapper<Organization> {
public Organization mapRow(ResultSet rs, int arg1) throws SQLException {
// TODO Auto-generated method stub
Organization org = new Organization();
org.setId(rs.getInt("id"));
org.setAddress(rs.getString("address"));
org.setName(rs.getString("name"));
org.setSlogan(rs.getString("slogan"));
org.setTotalEmployee(rs.getInt("totalEmployee"));
org.setYearOfIncorporation(rs.getInt("yearOfIncorporation"));
return org;
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vp.springdemo</groupId>
<artifactId>spring-jdbc-xml-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
</dependencies>
</project>
view raw pom.xml hosted with ❤ by GitHub



Above is the schema and the query of the schema is as below

CREATE TABLE `Organization` (
  `id` int(11) NOT NULL,
  `slogan` varchar(45) DEFAULT NULL,
  `totalEmployee` int(11) DEFAULT NULL,
  `yearOfIncorporation` int(11) DEFAULT NULL,
  `name` varchar(45) DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


You can download the full program from my git hub CLICK HERE


Hope this will help you in understanding the Coding part . If you face any issue please leave us a comment , Happy to help you :)


Thanks for reading
Noeik