spring中JdbcTemplate

9848 ワード

Springは各種の耐久化開発を簡略化するために、内部に多くのテンプレートツール類JDBC-org.springframe ebork.jdbc.co.ore.JdbcTemplate Hberg.org.springframe.ork.orm.orm.hibernete 3.HyBatis-org.springframe
Spring JDBCはSpringが提供する耐久層技術である.JDBC APIの開発を簡略化し、Apache社のDBUtilsフレームと非常に似ています.プロジェクトカタログにSpringコア開発パッケージを導入して、プロジェクトspring-beans-3.20.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-core-3.20.RELEASE.jar spring-jar spring-expressition-3.2.Emons.を開発する必要があります.包spring-jdbc-3.20.RELEASE.jar spring-tx-3.0.RELEASE.jar
データベースドライバmysql-connector-java-5.8-bin.jar
コード例:プロファイルを使わず、データベースを操作する
package com.my.jdbc;

import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class JdbcTemplateTest {
	
	@Test
	public void demo1(){
		// 1、              
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		//     ,    jdbc        
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring_demo");
		dataSource.setUsername("root");
		dataSource.setPassword("1234");
		
		// 2、     ,  JdbcTemplate   
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		
		// 3、  JdbcTemplate      
		jdbcTemplate.execute("create table user(id int, name varchar(20))");
	}

}

データベース接続プールの構成例:
appication Contect.xml


	
	
	







	






	
	
		
	
	
	
		
		
		
		
	
	
	
	
		
	
		

jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_demo
jdbc.username=root
jdbc.password=1234

テストクラスJdbcTemplateTest 2.java
package com.my.jdbc;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JdbcTemplateTest2 {

	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate ;
	
	@Test
	public void demo(){
		jdbcTemplate.execute("create table users0(id int)");
	}
	
}

JdbcTemplateを使ってDAOを作成してデータCURDコードの例を実現します.
package com.my.jdbc;

public class Customer {

	private int id;
	private String name; 
	private int age;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

sql文
CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CustoomerDao.java
package com.my.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

//  customer       
public class CustomerDao extends JdbcDaoSupport{ //   JdbcTemplate    

	//    
	public void save(Customer customer){
		String sql ="insert into customer values(null,?,?)";
		this.getJdbcTemplate().update(sql, customer.getName(),customer.getAge());
	}
	
	//  id  
	public void delete(Customer customer){
		String sql = "delete from customer where id = ?";
		this.getJdbcTemplate().update(sql, customer.getId());
	}
	
	//  id         
	public void update(Customer customer){
		String sql = "update customer set name=? , age=? where id =?";
		this.getJdbcTemplate().update(sql, customer.getName() , customer.getAge(), customer.getId());
	}
	
	//   id    age
	public int findAgeById(int id){
		String sql = "select age from customer where id = ?";
		return this.getJdbcTemplate().queryForInt(sql , id);
	}
	//   id   name
	public String findNameById(int id){
		String sql = "select name from customer where id = ?";
		return this.getJdbcTemplate().queryForObject(sql, String.class, id);
	}
	
	//         
	public List findAll(){
		String sql = "select * from customer";
		return this.getJdbcTemplate().query(sql, new CustomerRowMapper());
	}
	
	//   id         
	public Customer findById(int id){
		String sql = "select * from customer where id = ?";
		return this.getJdbcTemplate().queryForObject(sql, new CustomerRowMapper(), id);
	}
	
	private class CustomerRowMapper implements RowMapper {

		@Override
		public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
			Customer customer = new Customer(); 
			customer.setId(rs.getInt("id"));
			customer.setName(rs.getString("name"));
			customer.setAge(rs.getInt("age"));
			return customer;
		}
		
	}
	
	
}

appication Contect.xml



	
	
	
	
		
		
		
		
	
	
	
	
		
	
	
	
	
		
	
	

テストクラスTestCusmerDao.java
package com.my.jdbc;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestCustmerDao {

	@Autowired
	@Qualifier("customerDao")
	private CustomerDao customerDao ;
	
	@Test
	//       
	public void testSave(){
		Customer customer = new Customer();
		customer.setName("rose");
		customer.setAge(18);
		
		customerDao.save(customer);
	}
	
	@Test
	//       
	public void testUpdate(){
		Customer customer = new Customer();
		customer.setId(3);
		customer.setName("jack");
		customer.setAge(19);
		
		customerDao.update(customer);
	}
	
	@Test
	//        
	public void testDelete(){
		Customer customer = new Customer();
		customer.setId(1);
		
		customerDao.delete(customer);
	}
	
	@Test
	//        
	public void testFindAgeNameById(){
		System.out.println(customerDao.findAgeById(2));
		System.out.println(customerDao.findNameById(2));
	}
	
	@Test
	//       
	public void testFindAll(){
		System.out.println(customerDao.findAll());
		System.out.println(customerDao.findById(2));
	}
	
}