Spring – Ders 19 Spring & NamedParameterJdbcTemplate

Merhaba Arkadaslar,

Bu yazimizda Spring JDBC sablon siniflarindan ,NamedParameterJdbcTemplate yaklasimini uygulayacagiz. PreparedTemplateStatement yapisinda kullandigimiz ? isareti yerine column/alan isimlerini kullanabilmemizi saglar. Okunabirligi ve bakimi kolaylastirir.

String sql = "insert into student " + "(id, name, age) values (?, ?, ?)";

String query = "insert into student  (id_, name_, age_) values (:id,:name,:age)";

Daha onceki orneklerde kullandigimiz Student sinifinini burada da kullanacagiz.

Student.java

package erguder.levent._19.spring_namedparameterjdbctemplate;

public class Student {

	private int id;
	private String name;
	private int age;

	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	//getter setter 
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

Veritabanimizda tablomuzu yeniden olusturalim, burada dikkat ederseniz alan isimlerinden sonra altcizgi ekledim.

studenttable

Daha once de kullandigimiz RowMapper yapisini tekrar kullanacagiz ;

StudentMapper.java

package erguder.levent._19.spring_namedparameterjdbctemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> {
	@Override
	public Student mapRow(ResultSet rs, int rowNum) throws SQLException {

		Student student = new Student();
		student.setId(rs.getInt("id_"));
		student.setName(rs.getString("name_"));
		student.setAge(rs.getInt("age_"));
		return student;
	}
}

DAO arabirimizi tanimlayalim;

StudentDAO.java

package erguder.levent._19.spring_namedparameterjdbctemplate;

public interface StudentDAO {

	public void insertStudent(Student student);

	public Student selectStudent(int id);
}

Simdi de DAO arabimizi uygulayalim ;

StudentDAOImp.java

package erguder.levent._19.spring_namedparameterjdbctemplate;

import javax.sql.DataSource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

public class StudentDAOImp implements StudentDAO {

	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}

	@Override
	public void insertStudent(Student student) {

		String query = "insert into student  (id_, name_, age_) values (:id,:name,:age)";
		Map<String, Object> namedParameters = new HashMap<String, Object>();
		namedParameters.put("id", (student.getId()));
		namedParameters.put("name", student.getName());
		namedParameters.put("age", student.getAge());
		namedParameterJdbcTemplate.update(query, namedParameters);
	}

	@Override
	public Student selectStudent(int id) {
		String query = "select * from student where id_=:id";
		SqlParameterSource namedParameters = new MapSqlParameterSource("id", id );

		return (Student) namedParameterJdbcTemplate.queryForObject(query, namedParameters,new StudentMapper());

	}

}

PreparedStatement yapisina benzer sekilde insertStudent metodunda ? isareti yerine isim kullaniyoruz. Bir map anahtar/deger key/value yapisinda ekliyoruz.

SQL sorgumuzda dikkat edersek id_, name_ , age_ yani tabloda kullandigimiz column/alan adlarini gozardi etmiyoruz, values yapisinda ise parametrelere isim veriyoruz ve bu isimlerin karsiligini getter metotlarini kullanarak ekliyoruz.

selectStudent metodumuzda ise yine Spring in bize sagladigi MapSqlParameterSource sinifini kullaniyoruz. NamedParameterJdbcTemplate sinifinda bulunan queryForObject metoduna ilgili argumanlari vererek kullaniyoruz.

tutorial_19.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" 
    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="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/springjdbc"/>
      <property name="username" value="root"/>
      <property name="password" value=""/>
   </bean>

	<bean id="studentDAOid" class="erguder.levent._19.spring_namedparameterjdbctemplate.StudentDAOImp">
		<property name="dataSource" ref="dataSource"/>
	</bean>

</beans>

Daha onceki orneklerde kullandigimiz gibi DriverManagerDataSource sinifini ve ilgili alanlari kullanarak MySQL e springjdbc katalogumuza baglaniyoruz.
property etiketi ve ref ozelligi ile Spring wiring islemini gerceklestirmektedir.

TestSpringNamedParameterJdbcTemplate.java

package erguder.levent._19.spring_namedparameterjdbctemplate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpringNamedParameterJdbcTemplate {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("tutorial_19.xml");
		StudentDAO studentDAO = (StudentDAO) context.getBean("studentDAOid");
		Student springForum = new Student(1, "Levent Erguder", 24);

		studentDAO.insertStudent(springForum);
		System.out.println(studentDAO.selectStudent(1));
	}

}

Test sinifimizi calistirdigimizda ;
Student [id=1, name=Levent Erguder, age=24]

Yazimi burada sonlandiriyorum.

Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
injavawetrust

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *