本文共 7051 字,大约阅读时间需要 23 分钟。
本文旨在讲述Spring JDBC模块的用法。Spring JDBC模块是Spring框架的基础模块之一。
一、概述
在Spring JDBC模块中,所有的类可以被分到四个单独的包:@Configuration@ComponentScan("com.ch.myalbumjdbc")public class SpringJdbcConfig { @Bean public DataSource mysqlDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc"); dataSource.setUsername("guest_user"); dataSource.setPassword("guest_password"); return dataSource; }}
@Beanpublic DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .addScript("classpath:jdbc/schema.sql") .addScript("classpath:jdbc/test-data.sql").build();}
三、JdbcTemplate的使用和运行查询
1、基本的查询
JDBC模板是Spring JDBC模块中主要的API,它提供了常见的数据库访问功能:
int result = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class);
public int addEmplyee(int id) { return jdbcTemplate.update( "INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", 5, "Bill", "Gates", "USA");}
SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", 1);return namedParameterJdbcTemplate.queryForObject("SELECT FIRST_NAME FROM EMPLOYEE WHERE ID = :id", namedParameters, String.class);
Employee employee = new Employee();employee.setFirstName("James");String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName";SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee);return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID, namedParameters, Integer.class);
public class EmployeeRowMapper implements RowMapper { @Override public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getInt("ID")); employee.setFirstName(rs.getString("FIRST_NAME")); employee.setLastName(rs.getString("LAST_NAME")); employee.setAddress(rs.getString("ADDRESS")); return employee; }}
String query = "SELECT * FROM EMPLOYEE WHERE ID = ?";List employees = jdbcTemplate.queryForObject(query, new Object[] { id }, new EmployeeRowMapper());
public class CustomSQLErrorCodeTranslator extends SQLErrorCodeSQLExceptionTranslator { @Override protected DataAccessException customTranslate (String task, String sql, SQLException sqlException) { if (sqlException.getErrorCode() == -104) { return new DuplicateKeyException( "Custom Exception translator - Integrity constraint violation.", sqlException); } return null; }}
CustomSQLErrorCodeTranslator customSQLErrorCodeTranslator = new CustomSQLErrorCodeTranslator();jdbcTemplate.setExceptionTranslator(customSQLErrorCodeTranslator);
SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE");
public int addEmplyee(Employee emp) { Map parameters = new HashMap(); parameters.put("ID", emp.getId()); parameters.put("FIRST_NAME", emp.getFirstName()); parameters.put("LAST_NAME", emp.getLastName()); parameters.put("ADDRESS", emp.getAddress()); return simpleJdbcInsert.execute(parameters);}
SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource) .withTableName("EMPLOYEE") .usingGeneratedKeyColumns("ID");Number id = simpleJdbcInsert.executeAndReturnKey(parameters);System.out.println("Generated id - " + id.longValue());
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource) .withProcedureName("READ_EMPLOYEE");public Employee getEmployeeUsingSimpleJdbcCall(int id) { SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); Map out = simpleJdbcCall.execute(in); Employee emp = new Employee(); emp.setFirstName((String) out.get("FIRST_NAME")); emp.setLastName((String) out.get("LAST_NAME")); return emp;}
public int[] batchUpdateUsingJdbcTemplate(List employees) { return jdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setInt(1, employees.get(i).getId()); ps.setString(2, employees.get(i).getFirstName()); ps.setString(3, employees.get(i).getLastName()); ps.setString(4, employees.get(i).getAddress(); } @Override public int getBatchSize() { return 50; } });}
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(employees.toArray());int[] updateCounts = namedParameterJdbcTemplate.batchUpdate( "INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch);return updateCounts;
转载地址:http://ibtaa.baihongyu.com/