Note:
Before using these codes please follow the given guidelines
1. create a database newdb in MySQL server database
>> create database newdb;
3. create a table book inside newdb database
>> create table book (id int auto_increment,topic varchar(100) not null,author varchar(100) not null,cost float not null,primary key(id));
4. insert some records inside book table
>> insert into book (topic,author,cost) values('c','kanitkar','300');
>> insert into book (topic,author,cost) values('c++','pankaj','400');
Note:
This is a Data Transfer Object, Object of this class will be stored and fetched using DAO (Data Access Object, DAO is an approach to store and fetch object to and from the database)
<< code of Book.java starts >>
package beans;
public class Book
{
// data members
private int id;
private String topic, author;
private float cost;
// getters and setters public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getTopic()
{
return topic;
}
public void setTopic(String topic)
{
this.topic = topic;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public float getCost()
{
return cost;
}
public void setCost(float cost)
{
this.cost = cost;
}
// no argument constructor public Book()
{
}
// parameter constructor public Book(int id, String topic, String author, float cost)
{
this.id = id;
this.topic = topic;
this.author = author;
this.cost = cost;
}
}
package dao;
package dao;
// getter and setter for the JdbcTemplate class
// call the method of JdbcTemplte to execute the select query and fetch the object of bean
// (means the object of Book) from the database
package dao;
package tests;
Before using these codes please follow the given guidelines
1. create a database newdb in MySQL server database
>> create database newdb;
3. create a table book inside newdb database
>> create table book (id int auto_increment,topic varchar(100) not null,author varchar(100) not null,cost float not null,primary key(id));
4. insert some records inside book table
>> insert into book (topic,author,cost) values('c','kanitkar','300');
>> insert into book (topic,author,cost) values('c++','pankaj','400');
>> insert into book (topic,author,cost) values('java','nitin','500');
-----------------------------------------------------
Note:
This is a Data Transfer Object, Object of this class will be stored and fetched using DAO (Data Access Object, DAO is an approach to store and fetch object to and from the database)
Note ->
1. create a package beans
2. create class Book in beans package
3. copy and paste this code in Book
<< code of Book.java starts >>
public class Book
{
// data members
private int id;
private String topic, author;
private float cost;
// getters and setters public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getTopic()
{
return topic;
}
public void setTopic(String topic)
{
this.topic = topic;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public float getCost()
{
return cost;
}
public void setCost(float cost)
{
this.cost = cost;
}
// no argument constructor public Book()
{
}
// parameter constructor public Book(int id, String topic, String author, float cost)
{
this.id = id;
this.topic = topic;
this.author = author;
this.cost = cost;
}
}
<< code of Book.java ends >>
Note:
BookDAO is a Data Access Object (DAO) by which we will fetch and store the object of Book from and to the database.
DAO is just a guideline (means what to do?). The implementation of DAO (the class who implements this interface) will decide how to fetch and store the object.
Note ->
1. create a package dao
2. create interface BookDAO in dao package
3. copy and paste this code in BookDAO
<< code of BookDao.java starts >>
package dao;
import beans.Book;
public interface BookDAO
{
public abstract Book findBookById(int id);
}
<< code of BookDao.java ends >>
Note:
BookDAOImpl is the implementation of DAO.
Note ->
1. create a package dao
2. create class BookDAOImpl in dao package
3. copy and paste this code in BookDAOImpl
<< code of BookDAOImpl.java starts >>
package dao;
import org.springframework.jdbc.core.JdbcTemplate;
import beans.Book;
public class BookDAOImpl implements BookDAO
{
// object of JdbcTemplate class to execute the sql statements
// object of JdbcTemplate class to execute the sql statements
private JdbcTemplate tmp;
// getter and setter for the JdbcTemplate class
public JdbcTemplate getTmp()
{
return tmp;
}
public void setTmp(JdbcTemplate tmp)
{
this.tmp = tmp;
}
@Override
public Book findBookById(int id)
{
System.out.println("method of dao");
// create sql query
String sql = "SELECT * FROM BOOK WHERE id = ?";
// create query args
Object[] args = {id};
// create object of RowMapper
RowMapperImpl rm = new RowMapperImpl();
// call the method of JdbcTemplte to execute the select query and fetch the object of bean
// (means the object of Book) from the database
return tmp.queryForObject(sql,args,rm);
}
}
<< code of BookDAOImpl.java ends >>
Note:
RowMapperImpl is an implemenatsion of RowMapper interface. It is used to fetch and object from the database and store that inside the object of ResultSet. Then we fetch record from ResultSet and pass it to DAO using the object of bean (here the bean is Book ie. The DTO)
Note ->
1. create class RowMapperImpl in dao package
2. copy and paste this code in RowMapperImpl
<< code of RowMapperImpl .java starts >>
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import beans.Book;
public class RowMapperImpl implements RowMapper<Book>
{
@Override
public Book mapRow(ResultSet resultSet, int records)
throws SQLException
{
System.out.println("mapRow() executes");
System.out.println("Total records are "+records);
// create object of Book (book is a bean)
Book book = new Book();
// fetch data of column from the ResultSet and store
// it inside object of Book using setters
book.setId(resultSet.getInt("id"));
book.setTopic(resultSet.getString("topic"));
book.setAuthor(resultSet.getString("author"));
book.setCost(resultSet.getFloat("cost"));
// return the object of bean to the DAO
return book;
}
}
<< code of RowMapperImpl .java ends >>
Note:
dao.xml is used by the spring container in order to read the mapping for the dependency injection.
container creates object of bean using the mapping available inside this file.
<< code for dao.xml starts >
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- di for DriverManagerDataSource -->
<bean name="dm" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/navadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- di or JdbcTemplate -->
<bean name="jtemp" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dm"/>
</bean>
<!-- di for implementation of DAO -->
<bean name="dao" class="dao.BookDAOImpl">
<property name="tmp" ref="jtemp"/>
</bean>
</beans>
<< code of dao.xml file end>
Note:
In FetchObject.java we will start the spring container and will fetch object of DAO from it. After that we will fetch object of bean class (here the bean is Book) from the database by invoking the method of DAO.
Note ->
1. create a package tests
2. create a class FetchObject in tests package
3. copy and paste this code in FetchObject
<< code of FetchObject.java starts >>
package tests;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.EmptyResultDataAccessException;
import beans.Book;
import dao.BookDAOImpl;
public class FetchObject
{
public static void main(String[] args)
{
try
{
// start the spring container using xml file
ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext("dao.xml");
// fetch the object of DAO from the container
BookDAOImpl dao = (BookDAOImpl) ctx.getBean("dao");
// variable to store an Book id
int id = 3;
// invoke method of DAO to fetch object of Book from the database
Book b = dao.findBookById(id);
// fetch the data from the object of Book using getters and show it on console
System.out.println(b.getId());
System.out.println(b.getTopic());
System.out.println(b.getAuthor());
System.out.println(b.getCost());
}
// for invalid Book id the exception will be raised
catch(Exception e)
{
// check if exception was generated due to empty ResultSet
if(e instanceof EmptyResultDataAccessException)
{
System.out.println("invalid id");
}
}
} // end of main method
} // end of class
<< code of FetchObject.java ends >>
Thank you Sir, for this code.
ReplyDeleteWell explained code.. makes it easy for us to understand and run 👌
ReplyDeleteAwesome code...thank you sir.
ReplyDeleteAwesome code....thank you sir
ReplyDeleteThis makes me to understand Spring Well , Really Appreciable ,Keep On Doing Sir .....!!!,Fantabolous Code.
ReplyDelete:) :)