Spring – Ders 18 Spring & JdbcTemplate

Merhaba Arkadaslar,
Bir onceki yazimizda Spring ile JDBC kullanarak veritabanina ulasabilecegimizi ve islemler yapabilecegimizi gorduk. Spring , JDBC icin 3 adet template/sablon sinif tanimlar. Ilk olarak burada JdbcTemplate sinifini inceleyecegiz. JdbcTemplate , Spring’deki en temel sablon sinifidir.

Bir onceki ornekte kullandigimiz Student sinifimizi tekrar kullanacagiz. Student sinifimizda age, name, id degiskenleri ve getter/setter metotlarimiz olacak.

Student.java

package erguder.levent._18.jspring_jdbctemplate;

public class Student {
	private Integer age;
	private String name;
	private Integer id;

	public void setAge(Integer age) {
		this.age = age;
	}

	public Integer getAge() {
		return age;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getId() {
		return id;
	}
}

Spring in bize sagladigi RowMapper arabirimini uygulayacagiz , bu arabirim sayesinde ihtiyacimiza uygun olacak sekilde uygulayabiliriz.

StudentMapper.java

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

public class StudentMapper implements RowMapper<Student> {
   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;
   }
}

Simdide DAO(Data Access Object) arabimizi olusturalim. DAO ile kullanilan veritabanina erisim ve veri depolama islemi daha soyutlastirilarak,  diger katmanlarin veritabanina olan bagimliliklari azaltilir.

StudentDAO.java

package erguder.levent._18.jspring_jdbctemplate;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {

	public void setDataSource(DataSource ds);

	public void create(Integer id,String name, Integer age);

	public Student getStudent(Integer id);

	public List<Student> listStudents();

	public void delete(Integer id);

	public void update(Integer id, Integer age);
}

StudentDAO arabirimde tanimladigimiz metotlari uygulayalim ;

StudentJDBCTemplate.java

package erguder.levent._18.jspring_jdbctemplate;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class StudentJDBCTemplate implements StudentDAO {

	private DataSource dataSource;
	private JdbcTemplate jdbcTemplateObject;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplateObject = new JdbcTemplate(dataSource);
	}

	public void create(Integer id,String name, Integer age) {
		String SQL = "insert into Student (id,name, age) values (?,?, ?)";

		jdbcTemplateObject.update(SQL,id ,name, age);
		System.out.println("Created Record Name = " + name + " Age = " + age);
		return;
	}

	public Student getStudent(Integer id) {
		String SQL = "select * from Student where id = ?";
		Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentMapper());
		return student;
	}

	public List<Student> listStudents() {
		String SQL = "select * from Student";
		List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
		return students;
	}

	public void delete(Integer id) {
		String SQL = "delete from Student where id = ?";
		jdbcTemplateObject.update(SQL, id);
		System.out.println("Deleted Record with ID = " + id);
		return;
	}

	public void update(Integer id, Integer age) {
		String SQL = "update Student set age = ? where id = ?";
		jdbcTemplateObject.update(SQL, age, id);
		System.out.println("Updated Record with ID = " + id);
		return;
	}

}

Spring in bize sagladigi JdbcTemplate sinifini kullanacagiz.
create metodumuzu yeni bir kayit eklemek icin kullanacagiz.
getStudent metodumuzu Id degerine gore sorgulayip bilgileri getirecegiz.
listStudent metodumuzu tum kayitlari getirmek icin kullanacagiz.
delete metodumuzu ilgili Id li kaydi silmek icin kullanacagiz.
update metodumuzu ilgili Id li kaydin yasini guncellemek icin kullanacagiz.

tutorial_18.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="studentJDBCTemplate" 
      class="erguder.levent._17.jspring_jdbctemplate.StudentJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

</beans>

Bir onceki ornekte de kullandigimiz DriverManagerDataSource sinifini kullaniyoruz ve MySQL e baglantimizi kuruyoruz. Siz portu kullanici adini veya sifre degistirdiyseniz ona gore duzenlemek gerekir.

MySQL de student tablomuzu silip yeniden olusturalim ;

CREATE TABLE Student(
   ID   INT NOT NULL,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL
);

TestSpringJDBCTemplate.java

package erguder.levent._18.jspring_jdbctemplate;

import java.util.List;

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

public class TestSpringJDBCTemplate {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("tutorial_18.xml");

		StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

		System.out.println("------Eklenen Kayitlar--------");
		studentJDBCTemplate.create(1,"Ali", 2);
		studentJDBCTemplate.create(2,"Veli", 15);
		studentJDBCTemplate.create(3,"Ahmet",10);

		System.out.println("------Kayitlari Listele--------");
		List<Student> students = studentJDBCTemplate.listStudents();
		for (Student record : students) {
			System.out.print("ID : " + record.getId());
			System.out.print(", Name : " + record.getName());
			System.out.println(", Age : " + record.getAge());
		}

		System.out.println("----idsi 2 olan kaydin yasini guncelleyelim -----");
		studentJDBCTemplate.update(2, 20);

		System.out.println("----idsi 2 olan kaydin guncellenmis hali -----");
		Student student = studentJDBCTemplate.getStudent(2);
		System.out.print("ID : " + student.getId());
		System.out.print(", Name : " + student.getName());
		System.out.println(", Age : " + student.getAge());

		System.out.println("----idsi 2 olan kaydi silelim-----");
		studentJDBCTemplate.delete(2);

		System.out.println("------Kayitlari Listele--------");
	    students = studentJDBCTemplate.listStudents();
		for (Student record : students) {
			System.out.print("ID : " + record.getId());
			System.out.print(", Name : " + record.getName());
			System.out.println(", Age : " + record.getAge());
		}

	}
}

Test sinifimizi calistirip sonuclari gorelim ;

spring jdbc template

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.