You are on page 1of 6

=============>

what is spring jdbc ?


--
spring jdbc is a powerful mechanism to connect to the database and execute SQL
queries.
java program -> spring jdbc module(inside class is JdbcTemplate) -> database
spring jdbc internally use jdbc, also give more features.
*-*-*-*-*-*---*-*-
jdbc
--
jdbc is api to perform operation with database.
java program -> jdbc api(internally use driver ) -> database
*-*-*-*-*-*---*-*-
problems of jdbc ?
--
1. we need to write a lot of code. ( connection open -> statement -> execute ->
connection close )
2. Exception handling Problem:checked Exception (like SqlException problem..every
method we have to handle with try catch)
3. Repeating of all these codes from one database logic is a time consuming task.
*-*-*-*-*-*---*-*-
introduction to spring jdbc ?
----
solution of jdbc problems are provided by spring jdbc
sring jdbc provide class JdbcTemplate which has all the important methods to
perform operation with database.
jdbcTemplate object create(through this we can perform querieslike
insert,delete,select)
jdbcTemplate want dataSource,
DataSource is an interface, it contains all the information of the database. such
as url,username,password
DataSource implements class is DriverManagerDataSource ( DataSource -> implements -
> DriverManagerDataSource )
*-*-*-*-*-*---*-*-
how spring jdbc solves these problems ?
******************************************end
=============> create maven project adding spring jdbc dependency
---
add dependency of ( spring core and spring context & spring- jdbc ) so version
should be same
add MysqlConnector/postgresconnector , select any version ///update the maven
project
----
<!-- https://mvnrepository.com/artifact/org.springframework/spring-
context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.27</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.2</version>
</dependency>
*****************************************end
=============>
Database Setup.
Spring JDBC Configuration
JdbcTemplate and DataSource Setup
-----
create database springjdbc;
show databases;
---
use springjdbc;
create table student(id int primary key,
name varchar(100) not null,
city varchar(200));
show tables;
---
insert into student(id,name,city) values(1,'raja', "mumbai");
desc student;
-----------------------------------***********
com.spring.entity ---> Student class --id, name, city ; //default constructor, para
constructor, getter & setter , tostring() ... like pojo
object store in App class
config.xml
-----
<beans ..........>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name="ds"
>
//postgrey jdbc driver class name
<property name = "driveClassName" value = "com.mysql.jdbc.Driver />
<property name = "url" value = "jdbc:msql://Localhost:3306/springjdbc " />
<property name = "username" value = "postgrey" />
<property name = "password" value = "sb@1..5" />
//jdbc : is protocol, which technology we are using
//mysql : is subprotocol
// //Localhost:3306 : ip address ,which system db working, if db working on another
sysytem then we use ip address of that system
//database name:

// we will get package from jdbcTemplate class


<bean class="com.springframework.jdbc.core.JdbcTemplate " name/id="jdbcTemplate "
>
<property name="dataSource" ref="ds" />
</bean>
</beans>
*****************************end
inserting data to database using spring jdbc
=================>
package com.spring.jdbc;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class App {


public static void main( String[] args )
{
System.out.println( "Program started!" );
//spring jdbc => jdbcTemplate
ClassPathXmlApplicationContext con =
new
ClassPathXmlApplicationContext("com/spring/jdbc/collect.xml");
JdbcTemplate bean = con.getBean("jdbcTemplate",JdbcTemplate.class);

//insert query
String query ="insert into student(id,name,city)values(?,?,?)";

//fire the query


int result = bean.update(query,2,"subhash","pune");
System.out.println("number of record is inserted : "+result);
con.close();
}
}
-----------------this is not good approach to store/insert the record ../ This is
not recommended idea/approach
we will see best apprach to perform CRUD operation
establish connection with mysqlWorkbench/pgadmin
here we will follow some design pattern do.

com.spring.jdbc.dao -> (StudentDao(I)) -> public Student insert(Student student);


or public int insert(Student student);
com.spring.jdbc.dao -> StudentDaoImple implments StudentDao ( implement
unimplemented method).
create field obj of JdbcTemplate jdbcTemplate'; // getter setter
--in StudentDaoImpl
public int insert(Student student) {
//insert query
String query ="insert into student(id,name,city)values(?,?,?)";
int result =
this.jdbcTemplate.update(query,student.getId(),student.getName(),student.getCity())
;
return result;
}
--in xml add bean of StudentDaoImpl
<bean class="com.spring.jdbc.Dao.StudentDaoImpl" name="dao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
----app.java
public static void main( String[] args )
{
System.out.println( "Program started!" );
//spring jdbc => jdbcTemplate
ClassPathXmlApplicationContext con =
new
ClassPathXmlApplicationContext("com/spring/jdbc/collect.xml");
StudentDao bean = con.getBean("dao",StudentDao.class); //interface ref /
class ref
Student student = new Student();
student.setId(3);
student.setName("no name");
student.setCity("hif");
int result = bean.insert(student);
System.out.println("student added :" +result);
}
--------------------*******************
update operation using spring jdbc
==========>
studentDao -- public int update(Student student);

studentDaoImpl----
public int update(Student student) {
//update query
String query ="update student set name=?,city=? where id=?";
int result =
this.jdbcTemplate.update(query,student.getName(),student.getCity(),student.getId())
;
return result;
}
---app.java
Student student = new Student();
student.setId(3);
student.setName("no name");
student.setCity("hif");
int result = bean.update(student);
System.out.println("updated student :" +result);
}
-----------
delete operation using spring jdbc
==========>
studentDao -- public int delete(Student student);

studentDaoImpl----
public int delete(Student student) {
//delete query
String query ="delete from student where name=?;
int result = this.jdbcTemplate.update(query,student.getName());
syso("record is delete");
return result;
}
---app.java
Student student = new Student();
student.setName("no name");
int result = bean.delete(student);
System.out.println("deleted student :" +result);
}
**************************************************************
perform retrive/select operation using spring jdbc | selecting data using spring
jdbc
========================>
jdbc template methods
public T queryForObjecct(String sql, RowMapper<T>rowMapper, Object args)
public List<T> queryForObjecct(String sql, RowMapper<T>rowMapper)

what is row mapper ?


it converts result set to object
ResutSet Object -> Row Mapper ->class Object (Student)
here implementation Row Mapper
***********************************************************
selecting single object using spring jdbc
==================>
in StudentDao
-- public Student getStudent(int studentId);
in StudentDaoimpl
--public Student getStudent(int studentId){
//selecting single query
String query =" select * from student where id=?";
RowMapper<Student> rowmapper = new RowMapperImpl();
Student student = this.jdbcTemplate.queryForObject(query, rowMapper,
studentId);
return student;
}
---class RowMapperImpl implements RowMapper<Student>{
public Student mapRow(ResultSet rs,int rowNum)throws SQLException{
Student student = new Student();
student.setId(rs.getInt(1);
student.setName(rs.getString(2));
student.setCity(rs.getString(3));
return student;
}
--- app.java
Student student = StudentDao.getStudent(1);
syso(student);
******************************************
get all records
=========>
--in StudentDao -> public List<Student> getAllStudent();
--in impl ->
String query = "select * from student";
List<Student> student = this.jdbcTemplate.query(query, new
RowMapperImpl());
return student;
-- app.java
List<Student> allStudent = bean.getAllStudent();
for(Student s:allStudent) {
System.out.println(s);
******************************
no xml for configuration
=====>
@Configuration
public class JdbcConfig{

@Bean("ds")
public DriverMangerDataSource getDataSource(){
DriverMangerDataSource ds = new DriverMangerDataSource();
ds.setDriverclasName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://Localhost:3306/springjdbc");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}

@Bean("jdbcTemplate")
public JdbcTemplate getTemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(ds/ getDataSource());
return jdbcTemplate;
}

@Bean("studentDao")
public Studentdao getStudentdao(){
StudentDaoImpl studentDao = new StudentDaoImpl();
studentDao.setJdbctemplate(jdbcTemplate or getTemplate());
return studentDao;
}
}
*********************
use autowire in JdbcTemplate and on StudentDaoImple add @Component("studentdao")
**************************************

You might also like