Spring Jdbc concept
//StudentModel .java
package govind.icjs.curd;
public class StudentModel {
private Integer studentId;
private String studentName;
private String studentFatherName;
private String studentMotherName;
private Float marks;
private String percentage;
private String grade;
public StudentModel()
{
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentFatherName() {
return studentFatherName;
}
public void setStudentFatherName(String studentFatherName) {
this.studentFatherName = studentFatherName;
}
public String getStudentMotherName() {
return studentMotherName;
}
public void setStudentMotherName(String studentMotherName) {
this.studentMotherName = studentMotherName;
}
public Float getMarks() {
return marks;
}
public void setMarks(Float marks) {
this.marks = marks;
}
public String getPercentage() {
return percentage;
}
public void setPercentage(String percentage) {
this.percentage = percentage;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
===========================================================================================================================================================================================
//StudentDao .java
package govind.icjs.curd;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
public interface StudentDao {
public void setDataSource(DataSource ds);
public String saveStudentData(StudentModel studentmodel);
public String deleteStudentRecord(Integer studentId);
public String updateStudentRecord(StudentModel studentmodel);
public StudentModel getSingleStudentRecord(Integer studentId);
public List<StudentModel> getAllStudentRecord();
public List<StudentModel> getAllStudentRecordByOneHit();
Map<String, String> insertStudentdata(StudentModel studentmodel);
Map<String, String> updateStudentdata(StudentModel studentmodel);
Map<String, String> deleteStudentdata(Integer Studentid);
public List<StudentModel> getAllStudentList();
public List<StudentModel> getAllStudentList(Integer StudentId);
}
==============================================================================================================================================================================================
package govind.icjs.curd;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
public class StudentDaoImpl implements StudentDao{
private DataSource datasource;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private JdbcTemplate jdbcTemplate;
@Override
public void setDataSource(DataSource datasource) {
this.datasource=datasource;
this.namedParameterJdbcTemplate=new NamedParameterJdbcTemplate(datasource);
this.jdbcTemplate=new JdbcTemplate(datasource);
}
@Override
public String saveStudentData(StudentModel studentmodel) {
String sql="INSERT INTO student_namedparameter(student_name, student_fname, student_mname, marks,"
+" percentage, grade) VALUES (:student_name, :student_fname, :student_mname,:marks,:percentage,:grade) ";
SqlParameterSource namedParameters=new MapSqlParameterSource()
.addValue("student_name", studentmodel.getStudentName())
.addValue("student_fname",studentmodel.getStudentFatherName())
.addValue("student_mname", studentmodel.getStudentMotherName())
.addValue("marks", studentmodel.getMarks())
.addValue("percentage", studentmodel.getPercentage())
.addValue("grade", studentmodel.getGrade());
int insert = namedParameterJdbcTemplate.update(sql, namedParameters);
if(insert==1)
{
return "your data save successfully";
}
else
{
return "your data not save successfully";
}
}
@Override
public String deleteStudentRecord(Integer studentId) {
String sql="DELETE FROM student_namedparameter WHERE student_id=:student_id";
SqlParameterSource namedparameters=new MapSqlParameterSource("student_id",studentId);
int delete = namedParameterJdbcTemplate.update(sql, namedparameters);
if(delete==1)
{
return "your data deleted successfully";
}
else
{
return "Data Not Deleted";
}
}
@Override
public String updateStudentRecord(StudentModel studentmodel) {
String sql="UPDATE student_namedparameter SET student_id=:student_id,"
+ " student_name=:student_name, student_fname=:student_fname, student_mname=:student_mname,"
+ " marks=:marks, percentage=:percentage, grade=:grade"
+ " WHERE student_id=:student_id ";
//SqlParameterSource---->Interface
//MapSqlParameterSource---->Implemented class (i have method add value )
SqlParameterSource namedparameters=new MapSqlParameterSource().
addValue("student_name", studentmodel.getStudentName())
.addValue("student_fname", studentmodel.getStudentFatherName())
.addValue("student_mname", studentmodel.getStudentMotherName())
.addValue("marks", studentmodel.getMarks())
.addValue("percentage", studentmodel.getPercentage())
.addValue("grade", studentmodel.getGrade())
.addValue("student_id", studentmodel.getStudentId());
int updatebyid = namedParameterJdbcTemplate.update(sql, namedparameters);
if(updatebyid==1)
{
return "Your Data is Updated";
}
else
{
return "Your Data is Not Updated";
}
}
@Override
public StudentModel getSingleStudentRecord(Integer studentId) {
String sql="SELECT student_id, student_name, student_fname, student_mname, marks,"
+" percentage, grade FROM student_namedparameter where student_id=:student_id";
SqlParameterSource namedparameters=new MapSqlParameterSource("student_id",studentId);
StudentModel singlerecord = namedParameterJdbcTemplate.queryForObject(sql, namedparameters, new StudentMapper());
return singlerecord;
}
@Override
public List<StudentModel> getAllStudentRecord() {
String sql="SELECT student_id, student_name, student_fname, student_mname, marks,"
+" percentage, grade FROM student_namedparameter ";
List<StudentModel> allrecord = namedParameterJdbcTemplate.query(sql, new StudentMapper());
return allrecord;
}
//ResultSetExtractor implementation
@Override
public List<StudentModel> getAllStudentRecordByOneHit() {
return namedParameterJdbcTemplate.query("select * from student_namedparameter",new ResultSetExtractor<List<StudentModel>>()
{
@Override
public List<StudentModel> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<StudentModel> alldata=new ArrayList<StudentModel>();
while (rs.next())
{
StudentModel studentmodel=new StudentModel();
studentmodel.setStudentId(rs.getInt(1));
studentmodel.setStudentName(rs.getString(2));
studentmodel.setStudentFatherName(rs.getString(3));
studentmodel.setStudentMotherName(rs.getString(4));
studentmodel.setMarks(rs.getFloat(5));
studentmodel.setPercentage(rs.getString(6));
studentmodel.setGrade(rs.getString(7));
alldata.add(studentmodel);
}
return alldata;
}
});
}
@Override
public Map<String, String> insertStudentdata(StudentModel studentmodel) {
//SqlParameterSource interface and MapSqlParameterSource is implemented class
MapSqlParameterSource namedparameters=new MapSqlParameterSource();
Map<String, String> queryResult=new HashMap<>();
String sql="INSERT INTO student_namedparameter(student_name, student_fname, student_mname, marks,"
+" percentage, grade) VALUES (:student_name, :student_fname, :student_mname,:marks,:percentage,:grade) ";
namedparameters.addValue("student_name", studentmodel.getStudentName());
namedparameters.addValue("student_fname",studentmodel.getStudentFatherName());
namedparameters.addValue("student_mname", studentmodel.getStudentMotherName());
namedparameters.addValue("marks", studentmodel.getMarks());
namedparameters.addValue("percentage", studentmodel.getPercentage());
namedparameters.addValue("grade", studentmodel.getGrade());
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
int key = namedParameterJdbcTemplate.update(sql, namedparameters, keyHolder);
Map<String, Object> obj = keyHolder.getKeys();
int studentid =(int) obj.get("student_id");
if(key == 1){
queryResult.put("result", ""+studentid);
}
else
{
queryResult.put("rseult", "dberror");
}
} catch (Exception ex) {
queryResult.put("rseult", "dberror");
}
return queryResult;
}
@Override
public Map<String, String> updateStudentdata(StudentModel studentmodel) {
MapSqlParameterSource namedparameters=new MapSqlParameterSource();
Map<String, String> queryResult=new HashMap<>();
String sql="UPDATE student_namedparameter SET student_id=:student_id,"
+ " student_name=:student_name, student_fname=:student_fname, student_mname=:student_mname,"
+ " marks=:marks, percentage=:percentage, grade=:grade"
+ " WHERE student_id=:student_id ";
namedparameters.addValue("student_name", studentmodel.getStudentName());
namedparameters.addValue("student_fname", studentmodel.getStudentFatherName());
namedparameters.addValue("student_mname", studentmodel.getStudentMotherName());
namedparameters.addValue("marks", studentmodel.getMarks());
namedparameters.addValue("percentage", studentmodel.getPercentage());
namedparameters.addValue("grade", studentmodel.getGrade());
namedparameters.addValue("student_id", studentmodel.getStudentId());
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
int key = namedParameterJdbcTemplate.update(sql, namedparameters, keyHolder);
Map<String, Object> obj = keyHolder.getKeys();
int studentid =(int) obj.get("student_id");
if(key == 1){
queryResult.put("result", ""+studentid);
}else{
queryResult.put("rseult", "dberror");
}
} catch (Exception ex) {
//ex.printStackTrace();
queryResult.put("rseult", "dberror");
}
return queryResult;
}
@Override
public Map<String, String> deleteStudentdata(Integer studentid) {
MapSqlParameterSource namedparameters=new MapSqlParameterSource();
Map<String, String> queryResult=new HashMap<>();
String sql="DELETE FROM student_namedparameter"
+" WHERE student_id=:student_id";
namedparameters.addValue("student_id", studentid);
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
int key = namedParameterJdbcTemplate.update(sql, namedparameters, keyHolder);
Map<String, Object> obj = keyHolder.getKeys();
int stuid =(int) obj.get("student_id");
if(key == 1){
queryResult.put("result", ""+stuid);
}else{
queryResult.put("rseult", "dberror");
}
} catch (Exception ex) {
//ex.printStackTrace();
queryResult.put("rseult", "dberror");
}
return queryResult;
}
@Override
public List<StudentModel> getAllStudentList() {
List<StudentModel> studentlist=null;
String sql="SELECT student_id, student_name, student_fname, student_mname, marks,"
+" percentage, grade FROM student_namedparameter ";
try
{
studentlist = namedParameterJdbcTemplate.query(sql, new StudentMapper());
}
catch(DataAccessException ex)
{
ex.printStackTrace();
}
if(studentlist!=null && studentlist.size()>0)
{
return studentlist;
}
return studentlist;
}
@Override
public List<StudentModel> getAllStudentList(Integer StudentId) {
List<StudentModel> studentlist=null;
String sql="SELECT student_id, student_name, student_fname, student_mname, marks,"
+" percentage, grade FROM student_namedparameter where student_id=?";
try
{
studentlist = jdbcTemplate.query(sql, new Object[]{StudentId}, new StudentMapper());
}
catch(DataAccessException ex)
{
ex.printStackTrace();
}
if(studentlist!=null && studentlist.size()>0)
{
return studentlist;
}
return studentlist;
}
}
============================================================================================================================================================================================
//StudentMapper .java
package govind.icjs.curd;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.lang.model.util.Types;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<StudentModel>
{
@Override
public StudentModel mapRow(ResultSet rs, int arg1) throws SQLException {
StudentModel studentmodel=new StudentModel();
studentmodel.setStudentId(rs.getInt("student_id"));
studentmodel.setStudentName(rs.getString("student_name"));
studentmodel.setStudentFatherName(rs.getString("student_fname"));
studentmodel.setStudentMotherName(rs.getString("student_mname"));
studentmodel.setMarks(rs.getFloat("marks"));
studentmodel.setPercentage(rs.getString("percentage"));
studentmodel.setGrade(rs.getString("grade"));
return studentmodel;
}
}
================================================================================================================================================================================================
package govind.icjs.curd;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StudentMain {
public static void main(String[] args) {
ApplicationContext applicationcontext=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDaoImpl studentdaoimpl = (StudentDaoImpl)applicationcontext.getBean("sdaoimpl");
StudentModel studentmodel=new StudentModel();
studentmodel.setStudentName("sanjay");
studentmodel.setStudentFatherName("manjay jha");
studentmodel.setStudentMotherName("manisha jha");
studentmodel.setMarks(497.00f);
studentmodel.setPercentage("98.5%");
studentmodel.setGrade("A+");
/* System.out.println("---------------Insert Logic-----------------");
String insert =studentdaoimpl.saveStudentData(studentmodel);
System.out.println("***R u Happy Dear*** "+insert);*/
/* System.out.println("---------------Delete Logic-----------------");
String delete = studentdaoimpl.deleteStudentRecord(1);
System.out.println("***R u Happy Dear*** "+delete);*/
/* System.out.println("---------------Update Logic-----------------");
studentmodel.setStudentName("sanjeev jha");
studentmodel.setStudentFatherName("sadanand jha");
studentmodel.setStudentMotherName("shyama jha");
studentmodel.setMarks(476.00f);
studentmodel.setPercentage("96.5%");
studentmodel.setGrade("B");
studentmodel.setStudentId(12);*/
/* String update = studentdaoimpl.updateStudentRecord(studentmodel);
System.out.println("***R u Happy Dear*** "+update);
*/
/*System.out.println("----------------Get Single Record logic------------------");
StudentModel studentrecord = studentdaoimpl.getSingleStudentRecord(05);
System.out.println(studentrecord.getStudentName());
System.out.println(studentrecord.getStudentFatherName());
System.out.println(studentrecord.getStudentMotherName());
System.out.println(studentrecord.getMarks());
System.out.println(studentrecord.getPercentage());
System.out.println(studentrecord.getGrade());
*/
/*
System.out.println("----------------Retrieve All Record----------------------");
List<StudentModel> allrecord = studentdaoimpl.getAllStudentRecord();
int i=0;
for(StudentModel alldata:allrecord)
{
System.out.println("Record Number="+ ++i);
System.out.println(alldata.getStudentId());
System.out.println(alldata.getStudentName());
System.out.println(alldata.getStudentFatherName());
System.out.println(alldata.getStudentMotherName());
System.out.println(alldata.getMarks());
System.out.println(alldata.getPercentage());
System.out.println(alldata.getGrade());
}*/
//Resultset Extractor Implementation
/* System.out.println("----------------------Result Shows Through Result Set Extractor-----------------");
List<StudentModel> allstudentrecordbyonehit = studentdaoimpl.getAllStudentRecordByOneHit();
for(StudentModel kk:allstudentrecordbyonehit)
{
System.out.println(kk.getStudentId() +" "+kk.getStudentName()+" "+kk.getStudentFatherName()+" "+kk.getStudentMotherName()+" "+kk.getMarks()+" "+kk.getPercentage()+ " "+kk.getGrade());
}*/
/*Map<String, String> insert = studentdaoimpl.insertStudentdata(studentmodel);
if( insert.get("result").equalsIgnoreCase("dberror"))
{
System.out.println("Data Not save Successfully");
}
else
{
System.out.println("Data save Successfully");
}*/
/* Map<String, String> update = studentdaoimpl.updateStudentdata(studentmodel);
if( update.get("result").equalsIgnoreCase("dberror"))
{
System.out.println("Data Not Updated Successfully");
}
else
{
System.out.println("Data Updated Successfully");
}
*/
/*Map<String, String> delete = studentdaoimpl.deleteStudentdata(12);
if( delete.get("result").equalsIgnoreCase("dberror"))
{
System.out.println("Data Not Deleted Successfully");
}
else
{
System.out.println("Data Deleted Successfully");
}
*/
/* List<StudentModel> stulist = studentdaoimpl.getAllStudentList();
for(StudentModel stlist:stulist)
{
System.out.println(stlist.getStudentName()+" "+stlist.getStudentFatherName()+" "+stlist.getStudentMotherName()+ " "+stlist.getMarks()+" "+stlist.getPercentage()+ " "+stlist.getGrade());
}*/
/* List<StudentModel> stulist =studentdaoimpl.getAllStudentList(2);
for(StudentModel stlist:stulist)
{
System.out.println(stlist.getStudentName()+" "+stlist.getStudentFatherName()+" "+stlist.getStudentMotherName()+ " "+stlist.getMarks()+" "+stlist.getPercentage()+ " "+stlist.getGrade());
} */
}
}
===========================================================================================================================================================================================
//applicationContext.xml
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/govind" />
<property name="username" value="postgres" />
<property name="password" value="postgres" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
<bean id = "edaoimpl"
class = "govind.icjs.curd.EmployeeDaoImpl">
<property name = "dataSource" ref ="datasource" />
</bean>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="datasource"/>
</bean>
<bean id = "sdaoimpl"
class = "govind.icjs.curd.StudentDaoImpl">
<property name = "dataSource" ref ="datasource" />
</bean>
<bean id = "cdaoimpl"
class = "govind.icjs.curd.CollegeDaoImpl">
<property name = "dataSource" ref ="datasource" />
</bean>
</beans>