`
DavyJones2010
  • 浏览: 154318 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Spring JDBC: Introduction to JdbcTemplate (II)--API Usage

阅读更多

1. queryForMap

public Map<String, Object> queryForMap(String sql);
public Map<String, Object> queryForMap(String sql, Object... args);
public Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes);
// The methods above are meant to be s single row query.

As we can see from API Doc:

1) Return type is Map<String, Object>. One entry for each column, using the column name as the key.

2) As we cannot have  duplicate keys, this query is meant to be a single row query.

3) This methods is appropriate when you don't have a domain model, 

    Otherwise, consider using one of the queryForObject() methods.

4) If the row count that matches the sql is bigger than one, IncorrectResultSizeDataAccessException will be thrown.

package edu.xmu.jdbc.dao;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import edu.xmu.jdbc.bean.Student;

public class JdbcTemplateDao {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    }

    public void prepareData(List<Student> studentList) {
	String sql = "insert into student(name, age) values (?, ?)";
	for (Student student : studentList) {
	    jdbcTemplate
		    .update(sql,
			    new Object[] { student.getName(), student.getAge() },
			    new int[] { java.sql.Types.VARCHAR,
				    java.sql.Types.INTEGER });
	}
    }

    public Map<String, Object> queryForMap() {
	String sql = "select id, name, age from student";
	return jdbcTemplate.queryForMap(sql);
    }

    public Map<String, Object> queryForMap2(int id) {
	String sql = "select id, name, age from student where id=?";
	return jdbcTemplate.queryForMap(sql, new Object[] { id });
    }

    public Map<String, Object> queryForMap3(int id) {
	String sql = "select id, name, age from student where id<=?";
	return jdbcTemplate.queryForMap(sql, new Object[] { id },
		new int[] { java.sql.Types.INTEGER });
    }

    public void truncateTable() {
	String sql = "truncate table student";
	jdbcTemplate.execute(sql);
    }
}
package edu.xmu.jdbc.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import edu.xmu.jdbc.bean.Student;

public class JdbcTemplateTest {
    private DriverManagerDataSource dataSource;
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "root";
    private String password = "root";

    private JdbcTemplateDao dao;

    @Before
    public void setUp() {
	dataSource = new DriverManagerDataSource(url, username, password);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");

	dao = new JdbcTemplateDao();
	dao.setDataSource(dataSource);

	List<Student> studentList = new ArrayList<Student>();
	Student student = new Student("Davy", 24);
	studentList.add(student);

	dao.prepareData(studentList);
    }

    @Test
    public void queryForMapTest() {
	Map<String, Object> resultMap = dao.queryForMap();

	Set<Map.Entry<String, Object>> entrySet = resultMap.entrySet();
	for (Entry<String, Object> entryMap : entrySet) {
	    System.out.println(entryMap.getKey() + "=" + entryMap.getValue());
	}
    }

    @Test
    public void queryForMap2Test() {
	Map<String, Object> resultMap = dao.queryForMap2(1);

	Set<Map.Entry<String, Object>> entrySet = resultMap.entrySet();
	for (Entry<String, Object> entryMap : entrySet) {
	    System.out.println(entryMap.getKey() + "=" + entryMap.getValue());
	}
    }

    @Test
    public void queryForMap3Test() {
	Map<String, Object> resultMap = dao.queryForMap3(2);

	Set<Map.Entry<String, Object>> entrySet = resultMap.entrySet();
	for (Entry<String, Object> entryMap : entrySet) {
	    System.out.println(entryMap.getKey() + "=" + entryMap.getValue());
	}
    }

    @After
    public void tearDown() {
	dao.truncateTable();
    }
}
 

2. queryForObject

public <T> T queryForObject(String sql, Class<T> requiredType);
public <T> T queryForObject(String sql, Object[] args, Class<T> requiredType);
public <T> T queryForObject(String sql, Class<T> requiredType, Object... args);
// The methods above are meant to be a single row and single column query.
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType);
public <T> T queryForObject(String sql, RowMapper<T> rowMapper);
public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper);
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper);
//The methods above are meant to be a single row query.

As we can see from API Doc:

1) The methods without rowMapper params are meant to be a single row and single column query.

    Because the requiredType can only be java embedded type.

2) The methods with rowMapper params are meant to be a single row query.

package edu.xmu.jdbc.dao;

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

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import edu.xmu.jdbc.bean.Student;

public class QueryForObjectDao {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    }

    public void prepareData(List<Student> studentList) {
	String sql = "insert into student(name, age) values (?, ?)";
	for (Student student : studentList) {
	    jdbcTemplate
		    .update(sql,
			    new Object[] { student.getName(), student.getAge() },
			    new int[] { java.sql.Types.VARCHAR,
				    java.sql.Types.INTEGER });
	}
    }

    public Student queryForObject() {
	String sql = "select id from student";
	int id = jdbcTemplate.queryForObject(sql, Integer.class);

	sql = "select name from student";
	String name = jdbcTemplate.queryForObject(sql, String.class);

	sql = "select age from student";
	int age = jdbcTemplate.queryForObject(sql, Integer.class);

	return new Student(id, name, age);
    }

    public Student queryForObject2(int id) {
	String sql = "select name from student where id=?";
	String name = jdbcTemplate.queryForObject(sql, new Object[] { id },
		String.class);

	sql = "select age from student where id=?";
	int age = jdbcTemplate.queryForObject(sql, new Object[] { id },
		Integer.class);

	return new Student(id, name, age);
    }

    public Student queryForObject3(int id) {
	String sql = "select name from student where id=?";
	String name = jdbcTemplate.queryForObject(sql, new Object[] { id },
		new int[] { java.sql.Types.INTEGER }, String.class);

	sql = "select age from student where id=?";
	int age = jdbcTemplate.queryForObject(sql, new Object[] { id },
		new int[] { java.sql.Types.INTEGER }, Integer.class);

	return new Student(id, name, age);
    }

    /**
     * This sql is meant to be a single row result set. <br/>
     * If result set size is bigger than 1,
     * IncorrectResultSizeDataAccessException will be thrown.
     * 
     * @return
     */
    public Student queryForObject4() {
	String sql = "select id, name, age from student";

	Student student = jdbcTemplate.queryForObject(sql,
		new RowMapper<Student>() {

		    public Student mapRow(ResultSet rs, int rowNum)
			    throws SQLException {
			// int id = rs.getInt("id");
			int id = rs.getInt(1);
			// String name = rs.getString("name");
			String name = rs.getString(2);
			// int age = rs.getInt("age");
			int age = rs.getInt(3);

			return new Student(id, name, age);
		    }

		});

	return student;
    }

    public Student queryForObject5(int id) {
	String sql = "select id, name, age from student where id=?";
	Student student = jdbcTemplate.queryForObject(sql, new Object[] { id },
		new RowMapper<Student>() {

		    public Student mapRow(ResultSet rs, int rowNum)
			    throws SQLException {
			int id = rs.getInt(1);
			String name = rs.getString(2);
			int age = rs.getInt(3);
			return new Student(id, name, age);
		    }

		});

	return student;
    }

    public Student queryForObject6(int id) {
	String sql = "select id, name, age from student where id=?";
	Student student = jdbcTemplate.queryForObject(sql, new Object[] { id },
		new int[] { java.sql.Types.INTEGER }, new RowMapper<Student>() {

		    public Student mapRow(ResultSet rs, int rowNum)
			    throws SQLException {
			int id = rs.getInt(1);
			String name = rs.getString(2);
			int age = rs.getInt(3);
			return new Student(id, name, age);
		    }

		});

	return student;
    }

    public void truncateTable() {
	String sql = "truncate table student";
	jdbcTemplate.execute(sql);
    }
}
package edu.xmu.jdbc.dao;

import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import edu.xmu.jdbc.bean.Student;

public class QueryForObjectTest {
    private DriverManagerDataSource dataSource;
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "root";
    private String password = "root";

    private QueryForObjectDao dao;

    @Before
    public void setUp() {
	dataSource = new DriverManagerDataSource(url, username, password);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");

	dao = new QueryForObjectDao();
	dao.setDataSource(dataSource);

	List<Student> studentList = new ArrayList<Student>();
	Student student = new Student("Davy", 24);
	studentList.add(student);

	dao.prepareData(studentList);
    }

    @Test
    public void queryForObjectTest() {
	Student student = dao.queryForObject();
	System.out.println(student);
    }

    @Test
    public void queryForObject2Test() {
	Student student = dao.queryForObject2(1);
	System.out.println(student);
    }

    @Test
    public void queryForObject3Test() {
	Student student = dao.queryForObject3(1);
	System.out.println(student);
    }

    @Test
    public void queryForObject4Test() {
	Student student = dao.queryForObject4();
	System.out.println(student);
    }

    @Test
    public void queryForObject5Test() {
	Student student = dao.queryForObject5(1);
	System.out.println(student);
    }

    @Test
    public void queryForObject6Test() {
	Student student = dao.queryForObject6(1);
	System.out.println(student);
    }

    @After
    public void tearDown() {
	dao.truncateTable();
    }
}

 

3. queryForList

// Return a list of Map, with the key of column name, and value of column value.
// The methods below are especially userful when we don't have a domain model.
public List<Map<String, Object>> queryForList(String sql);
public List<Map<String, Object>> queryForList(String sql, Object... args);
public List<Map<String, Object>> queryForList(String sql, Object[] args, int[] argTypes);

// Return a list of Object, with the type of elementType.
// This method is meant to be a single column query.
// And the elementType can be only java embedded type.
public <T> List<T> queryForList(String sql, Class<T> elementType);
public <T> List<T> queryForList(String sql, Object[] args, Class<T> elementType);
public <T> List<T> queryForList(String sql, Class<T> elementType, Object... args);
public <T> List<T> queryForList(String sql, Object[] args, int[] argTypes, Class<T> elementType);

// Although this method is not queryForList, but it is meant for quering for a 
// list of customized element.
public <T> List<T> query(String sql, RowMapper<T> rowMapper);

As we can see from API Doc:

1) If we want to return a list of primary element, we can use queryForList.

    But if we need return a list of customized element, we can use query(sql, rowMapper) instead.

2) The first segment of methods are appropriate when you don't have a domain model.

    They can be seen as an enhancement for queryForMap().

package edu.xmu.jdbc.dao;

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

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import edu.xmu.jdbc.bean.Student;

public class QueryForListDao {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    }

    public void prepareData(List<Student> studentList) {
	String sql = "insert into student(name, age) values (?, ?)";
	for (Student student : studentList) {
	    jdbcTemplate
		    .update(sql,
			    new Object[] { student.getName(), student.getAge() },
			    new int[] { java.sql.Types.VARCHAR,
				    java.sql.Types.INTEGER });
	}
    }

    public List<Map<String, Object>> queryForList(int id) {
	String sql = "select id, name, age from student where id<=?";
	List<Map<String, Object>> returnList = jdbcTemplate.queryForList(sql,
		new Object[] { id });

	return returnList;
    }

    public List<String> queryForList2(int id) {
	String sql = "select name from student where id<=?";
	List<String> returnList = jdbcTemplate.queryForList(sql,
		new Object[] { id }, String.class);
	return returnList;
    }

    /**
     * Although query is not query for list, <br/>
     * here it performs just like queryForList. <br/>
     * And we use queryForList can never get a list of customized bean.
     * 
     * @param id
     * @return
     */
    public List<Student> query(int id) {
	String sql = "select id, name, age from student where id<=?";

	List<Student> returnList = jdbcTemplate.query(sql, new Object[] { id },
		new RowMapper<Student>() {

		    public Student mapRow(ResultSet rs, int rowNum)
			    throws SQLException {
			int id = rs.getInt("id");
			String name = rs.getString("name");
			int age = rs.getInt("age");
			return new Student(id, name, age);
		    }

		});

	return returnList;
    }

    public void truncateTable() {
	String sql = "truncate table student";
	jdbcTemplate.execute(sql);
    }
}
package edu.xmu.jdbc.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import edu.xmu.jdbc.bean.Student;

public class QueryForListTest {
    private DriverManagerDataSource dataSource;
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "root";
    private String password = "root";

    private QueryForListDao dao;

    @Before
    public void setUp() {
	dataSource = new DriverManagerDataSource(url, username, password);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");

	dao = new QueryForListDao();
	dao.setDataSource(dataSource);

	List<Student> studentList = new ArrayList<Student>();
	Student student = new Student("Davy", 24);
	studentList.add(student);
	student = new Student("Jones", 25);
	studentList.add(student);

	dao.prepareData(studentList);
    }

    @Test
    public void queryForListTest() {
	List<Map<String, Object>> resultList = dao.queryForList(2);

	for (Map<String, Object> resultMap : resultList) {
	    Set<Map.Entry<String, Object>> entrySet = resultMap.entrySet();
	    for (Map.Entry<String, Object> entry : entrySet) {
		System.out.println(entry.getKey() + " = " + entry.getValue());
	    }
	}
    }

    @Test
    public void queryForList2Test() {
	List<String> nameList = dao.queryForList2(2);
	for (String name : nameList) {
	    System.out.println("name = " + name);
	}
    }

    @Test
    public void queryForList3Test() {
	List<Student> studentList = dao.query(2);
	for (Student student : studentList) {
	    System.out.println(student);
	}
    }

    @After
    public void tearDown() {
	dao.truncateTable();
    }
}

 

4. query

// ResultSetExtractor
public <T> T query(final String sql, final ResultSetExtractor<T> rse);
public <T> T query(String sql, Object[] args, ResultSetExtractor<T> rse);
public <T> T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor<T> rse);

// RowMapper
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper);
public <T> List<T> query(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper);

// RowCallBackHandler
public void query(String sql, RowCallbackHandler rch);
public void query(String sql, Object[] args, RowCallbackHandler rch);
public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch);

We need to know the different representation of ResultSetExtractor & RowMapper & RowCallBackHandler

1> Example for ResultSetExtractor

2> Example for RowMapper

3> Example for RowCallbackHandler

package edu.xmu.jdbc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
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 edu.xmu.jdbc.bean.Student;

public class QueryDao {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    }

    public void prepareData(List<Student> studentList) {
	String sql = "insert into student(name, age) values (?, ?)";
	for (Student student : studentList) {
	    jdbcTemplate
		    .update(sql,
			    new Object[] { student.getName(), student.getAge() },
			    new int[] { java.sql.Types.VARCHAR,
				    java.sql.Types.INTEGER });
	}
    }

    /**
     * If we want to get a Map<Integer, Student> <br/>
     * Key: StudentId, as it is identical <br/>
     * Value: Student <br/>
     * 
     * The problem is that if we use query(), <br/>
     * we will get List<Map<Integer, Student>> <br/>
     * Then we have to convert this structure to single map. <br/>
     * 
     * With ResultSetExtractor, we can avoid convertion <br/>
     * 
     * @param id
     */
    public Map<Integer, Student> queryWithResultSetExtractor(int id) {
	String sql = "select id, name, age from student where id <= ?";

	return jdbcTemplate.query(sql, new Object[] { id },
		new ResultSetExtractor<Map<Integer, Student>>() {

		    public Map<Integer, Student> extractData(ResultSet rs)
			    throws SQLException, DataAccessException {
			Map<Integer, Student> studentMap = new HashMap<Integer, Student>();

			while (rs.next()) {
			    int id = rs.getInt("id");
			    String name = rs.getString("name");
			    int age = rs.getInt("age");

			    Student student = new Student(id, name, age);
			    studentMap.put(id, student);
			}

			return studentMap;
		    }

		});
    }

    /**
     * Here we user RowMapper as a comparator with previous one. <br/>
     * We are sure that every map inside the list have only one entry. <br/>
     * 
     * @param id
     * @return
     */
    public List<Map<Integer, Student>> queryWithRowMapper(int id) {
	String sql = "select id, name, age from student where id<=?";

	return jdbcTemplate.query(sql, new Object[] { id },
		new RowMapper<Map<Integer, Student>>() {

		    public Map<Integer, Student> mapRow(ResultSet rs, int rowNum)
			    throws SQLException {
			Map<Integer, Student> map = new HashMap<Integer, Student>();

			int id = rs.getInt(1);
			String name = rs.getString(2);
			int age = rs.getInt(3);
			Student student = new Student(id, name, age);
			map.put(id, student);

			return map;
		    }

		});
    }

    public void truncateTable() {
	String sql = "truncate table student";
	jdbcTemplate.execute(sql);
    }
}
package edu.xmu.jdbc.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import edu.xmu.jdbc.bean.Student;

public class QueryDaoTest {
    private DriverManagerDataSource dataSource;
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "root";
    private String password = "root";

    private QueryDao dao;

    @Before
    public void setUp() {
	dataSource = new DriverManagerDataSource(url, username, password);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");

	dao = new QueryDao();
	dao.setDataSource(dataSource);

	List<Student> studentList = new ArrayList<Student>();
	Student student = new Student("Davy", 24);
	studentList.add(student);
	student = new Student("Jones", 25);
	studentList.add(student);

	dao.prepareData(studentList);
    }

    @Test
    public void queryWithResultSetExtractorTest() {
	Map<Integer, Student> studentMap = dao.queryWithResultSetExtractor(2);
	Set<Entry<Integer, Student>> entrySet = studentMap.entrySet();
	for (Entry<Integer, Student> entry : entrySet) {
	    int id = entry.getKey();
	    Student student = entry.getValue();
	    System.out.println("ID: " + id + ", Student: " + student);
	}
    }

    @Test
    public void queryWithRowMapperTest() {
	List<Map<Integer, Student>> list = dao.queryWithRowMapper(2);

	for (Map<Integer, Student> map : list) {
	    Set<Entry<Integer, Student>> set = map.entrySet();

	    for (Entry<Integer, Student> entry : set) {
		int id = entry.getKey();
		Student student = entry.getValue();
		System.out.println("ID: " + id + ", Student: " + student);
	    }
	}
    }

    @After
    public void tearDown() {
	dao.truncateTable();
    }
}

 

5. update

public int update(final String sql);
public int update(String sql, Object... args);
public int update(String sql, Object[] args, int[] argTypes);

1) Update can be used for CUD operation.

2) Return int represents the number of rows affected

package edu.xmu.jdbc.dao;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import edu.xmu.jdbc.bean.Student;

public class UpdateDao {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    }

    public void prepareData(List<Student> studentList) {
	String sql = "insert into student(name, age) values (?, ?)";
	for (Student student : studentList) {
	    jdbcTemplate
		    .update(sql,
			    new Object[] { student.getName(), student.getAge() },
			    new int[] { java.sql.Types.VARCHAR,
				    java.sql.Types.INTEGER });
	}
    }

    public void updateForUpdate(int id, Student student) {
	String name = student.getName();
	int age = student.getAge();

	String sql = "update student set name=?, age=? where id=?";

	jdbcTemplate.update(sql, new Object[] { name, age, id });
    }

    public void updateForDelete(int id) {
	String sql = "delete from student where id=?";

	jdbcTemplate.update(sql, new Object[] { id });
    }

    public void truncateTable() {
	String sql = "truncate table student";
	jdbcTemplate.execute(sql);
    }
}
package edu.xmu.jdbc.dao;

import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import edu.xmu.jdbc.bean.Student;

public class UpdateDaoTest {
    private DriverManagerDataSource dataSource;
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "root";
    private String password = "root";

    private UpdateDao dao;

    @Before
    public void setUp() {
	dataSource = new DriverManagerDataSource(url, username, password);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");

	dao = new UpdateDao();
	dao.setDataSource(dataSource);

	List<Student> studentList = new ArrayList<Student>();
	Student student = new Student("Davy", 24);
	studentList.add(student);
	student = new Student("Jones", 25);
	studentList.add(student);

	dao.prepareData(studentList);
    }

    @Test
    public void updateForUpdateTest() {
	int id = 1;
	String updatedName = "Caly";
	int updatedAge = 22;

	Student student = new Student(updatedName, updatedAge);

	dao.updateForUpdate(id, student);
    }

    @Test
    public void updateForDeleteTest() {
	dao.updateForDelete(2);
    }

    @After
    public void tearDown() {
	dao.truncateTable();
    }
}

 

6. Depreciated methods

@Deprecated
public int queryForInt(String sql);
@Deprecated
public int queryForInt(String sql, Object... args);
@Deprecated
public int queryForInt(String sql, Object[] args, int[] argTypes)

@Deprecated
public long queryForLong(String sql);
@Deprecated
public long queryForLong(String sql, Object... args);
@Deprecated
public long queryForLong(String sql, Object[] args, int[] argTypes)

We can find the reason why they are depreciated by following url listed below.

 

7. DDL Execution

// This method is often used for DDL statements
public void execute(final String sql);

As we can infer from the official document that as convention, we use execute(String) method to execute ddl.

But executing DDL programatically is depreciated.

It is a good practice to only execute CRUD in program and left DDL to be executed by DBA.

package edu.xmu.jdbc.dao;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class DDLDao {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    }

    public void createTable() {
	String sql = "create table student_bak (id int primary key auto_increment, name varchar(100), age int)";
	jdbcTemplate.execute(sql);
    }

    public void deleteTable() {
	String sql = "drop table student_bak";
	jdbcTemplate.execute(sql);
    }

    public void alterTable() {
	String sql = "alter table student_bak add score decimal, add gender varchar(100)";
	jdbcTemplate.execute(sql);
    }
}
package edu.xmu.jdbc.dao;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class DDLDaoTest {
    private DriverManagerDataSource dataSource;
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "root";
    private String password = "root";

    private DDLDao dao;

    @Before
    public void setUp() {
	dataSource = new DriverManagerDataSource(url, username, password);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");

	dao = new DDLDao();
	dao.setDataSource(dataSource);
    }

    @Test
    public void createTableTest() {
	dao.createTable();
    }

    @Test
    @Ignore
    public void deleteTableTest() {
	dao.deleteTable();
    }

    @Test
    public void alterTableTest() {
	dao.alterTable();
    }
}

 

 

Reference Links:

1) http://stackoverflow.com/questions/15661313/jdbctemplate-queryforint-long-is-deprecated-in-spring-3-2-2-what-should-it-be-r Why queryForInt/Long are depreciated?

2) http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html Spring JDBC Template official document.

分享到:
评论

相关推荐

    spring-jdbc jar包.rar

    1. **JdbcTemplate**:这是Spring JDBC的核心类,它通过模板方法模式将常见的JDBC操作进行了封装,如执行SQL查询、更新、调用存储过程等。开发者只需要关注SQL语句和参数,而无需处理连接创建、关闭、异常处理等繁琐...

    spring对jdbc的支持jar包

    1. **JdbcTemplate**:这是Spring JDBC的基础组件,它通过模板方法模式封装了常见的JDBC操作,如执行SQL查询、更新、存储过程等。使用JdbcTemplate,开发者无需手动管理数据库连接、预编译语句、结果集转换等细节,...

    Spring Data JDBC与JDBC的区别

    Spring Data JDBC与JDBC是两种不同的数据库访问方式,它们在Java开发中有着广泛的应用。JDBC(Java Database Connectivity)是Java平台的标准API,用于与各种数据库进行交互。它提供了低级别的数据库操作,如建立...

    SpringJDBC.rar_SpringJDBC_jdbctemplate_jdbctemplate spring

    Spring JDBC通过提供JdbcTemplate和SimpleJdbcTemplate等工具类,帮助开发者以更安全、更易于管理的方式与数据库进行交互,降低了传统JDBC代码的复杂性。下面我们将详细探讨Spring JDBC的核心概念、工作原理以及如何...

    spring jdbc.zip

    Spring JDBC的目标是减少传统JDBC代码的复杂性和易错性,通过提供一套高级API来封装JDBC的底层细节。这使得开发者能够更专注于业务逻辑,而不是繁琐的数据访问层实现。Spring JDBC不仅包含了JDBC的基本功能,如数据...

    Spring JDBC相关jar包:spring_jdbc_4.0.0.zip

    总之,Spring JDBC 4.0.0版本的`JdbcTemplate`是Spring框架在数据库操作方面的重要工具,它的设计哲学是简化JDBC编程,提供更安全、更易用的API,以帮助开发者更高效地管理数据库操作。通过这个压缩包中的“spring-...

    Spring JDBC模板类—org.springframework.jdbc.core.JdbcTemplate

    Spring JDBC模板类——`org.springframework.jdbc.core.JdbcTemplate`是Spring框架中的核心组件,它为Java开发者提供了一种方便、安全的方式来执行SQL语句,而无需直接管理数据库连接。`JdbcTemplate`通过抽象出低...

    spring-jdbcTemplate实例工程

    总的来说,Spring JdbcTemplate是Spring框架中处理数据库操作的重要工具,它通过简化JDBC API,提升了开发效率和代码质量。在实际项目中,结合Spring的其他组件,可以构建出稳定、高效的数据访问层。这个实例工程为...

    spring-boot-jdbc:spring-boot-jdbc

    Spring Boot JDBC是Spring框架的一个重要组成部分,它简化了在Java应用程序中使用JDBC(Java Database Connectivity)进行数据库操作的方式。Spring Boot的设计理念是“约定优于配置”,因此它为开发者提供了开箱即...

    Spring-JDBC整合-MySQL8、java8版本

    Spring JDBC 提供了 JdbcTemplate 和 NamedParameterJdbcTemplate,这两个工具类极大地减少了我们处理数据库连接、事务管理、结果集映射等工作所需的手动编码。 首先,集成Spring JDBC需要引入相应的jar包。在现代...

    spring jdbcTemplet demo

    Spring JDBCTemplate是一个强大的工具,它是Spring框架的一部分,用于简化Java数据库连接(JDBC)操作。在本示例中,我们将深入探讨Spring JDBCTemplate的工作原理、优势以及如何在实际项目中进行配置和使用。 首先...

    spring-jdbc-4.2.xsd.zip

    `spring-jdbc-4.2.xsd`是Spring 4.2版本的JDBC配置XML Schema定义,它定义了一系列元素和属性,用来描述如何配置Spring的JdbcTemplate、NamedParameterJdbcTemplate、SimpleJdbcInsert等核心组件,以及事务管理相关...

    spring jdbc相关包版本5.1.3

    Spring JDBC简化了数据库操作,例如,通过`JdbcTemplate`可以方便地执行SQL语句,进行增删改查操作。同时,Spring的事务管理功能(`PlatformTransactionManager`)可以确保在多条数据库操作之间保持事务的原子性。在...

    spring-jdbc(jdbctemplate)所需jar包

    JdbcTemplate是Spring JDBC模块中的核心组件,它提供了一种模板化的JDBC操作方式,降低了数据库访问的复杂性,同时保持了良好的封装和异常处理机制。在使用Spring JDBC之前,我们需要确保引入了必要的jar包。这里...

    spring JDbc

    在本实例中,我们将深入探讨Spring JDBC的使用,并以`SpringJdbcTemplate`为例来阐述其主要功能和优势。 首先,Spring JDBC通过`JdbcTemplate`和`NamedParameterJdbcTemplate`类提供了强大的数据库访问功能。`...

    jdbcTemplate-spring对jdbc的支持

    标题 "jdbcTemplate-spring对jdbc的支持" 涉及到的是Spring框架中的一个核心组件——JdbcTemplate,它是Spring对Java数据库连接(JDBC)的一种封装,用于简化数据库操作。JdbcTemplate提供了一种模板方法模式,使得...

    4.Spring中的JdbcTemplate,Spring中的的事务,

    通过封装原生的JDBC API,JdbcTemplate不仅提高了代码的可读性和可维护性,还帮助开发者避免了许多常见的错误,比如资源关闭、SQL注入等问题。 Spring框架提供了多种模板类来处理不同的数据访问需求,例如...

    SpringJDBC.rar_jdbc spring_spring jd_spring jdbc_spring使用JDBC进行数

    3. **SimpleJdbcTemplate**:这是JdbcTemplate的一个简化版本,为非注解的Java代码提供了更简洁的API,同样能处理大部分的JDBC任务。 4. **NamedParameterJdbcTemplate**:对于包含命名参数的SQL语句,这个类提供了...

    基于spring jdbc的上层封装,底层jdbc操作基于JdbcTemplate

    基于spring jdbc的上层封装,底层jdbc操作基于JdbcTemplate,支持MySql、SqlServer、Oracle数据库,强弱类型完美结合 1、mini-jdbc:针对spring jdbc的一些不方便的地方,做了一些封装,大小写不敏感,简化了日常的...

    spring jdbc 常用jar包

    Spring提供了两种使用JDBC API的最佳实践,一种是以JdbcTemplate为核心的基于Template的JDBC的使用方式,另一种则是在JdbcTemplate基础之上的构建的基于操作对象的JDBC的使用方式。

Global site tag (gtag.js) - Google Analytics