日期:2014-05-16 浏览次数:20459 次
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection conn) throws SQLException { String sql = "insert into vehicle(PLATE,CHASSIS,COLOR,WHEEL,SEAT) values(?,?,?,?,?)"; PreparedStatement pstat = conn.prepareStatement(sql); pstat.setString(1, vehicle.getPlate()); pstat.setString(2, vehicle.getChassis()); pstat.setString(3, vehicle.getColor()); pstat.setInt(4, vehicle.getWheel()); pstat.setInt(5, vehicle.getSeat()); return pstat; } }, keyHolder); System.out.println("PK: " + keyHolder.getKey().intValue());
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String sql = "insert into vehicle(PLATE,CHASSIS,COLOR,WHEEL,SEAT) values(?,?,?,?,?)"; jdbcTemplate.update(sql, vehicle.getPlate(), vehicle.getChassis(), vehicle.getColor(), vehicle.getWheel(), vehicle.getSeat()); int id = jdbcTemplate.queryForInt("CALL IDENTITY()"); System.out.println("PK: " + id);
public void insertBatch(final List<Vehicle> vehicles) { String sql = "insert into vehicle(PLATE,CHASSIS,COLOR,WHEEL,SEAT) values(?,?,?,?,?)"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement pstat, int i) throws SQLException { Vehicle vehicle = vehicles.get(i); pstat.setString(1, vehicle.getPlate()); pstat.setString(2, vehicle.getChassis()); pstat.setString(3, vehicle.getColor()); pstat.setInt(4, vehicle.getWheel()); pstat.setInt(5, vehicle.getSeat()); } public int getBatchSize() { return vehicles.size(); } }); }
public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath:org/ourpioneer/vehicle/spring/applicationContext.xml"); VehicleDAO vehicleDAO = (VehicleDAO) ctx.getBean("vehicleDAO"); Vehicle vehicle1 = new Vehicle("辽B-000000", "1A00000001", "RED", 4, 4); Vehicle vehicle2 = new Vehicle("辽B-000001", "1A00000002", "RED", 4, 4); vehicleDAO.insertBatch(Arrays .asList(new Vehicle[] { vehicle1, vehicle2 })); }
public Vehicle findById(int id) { String sql = "select * from vehicle where ID=?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final Vehicle vehicle = new Vehicle(); jdbcTemplate.query(sql, new Object[] { id }, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { vehicle.setId(rs.getInt("ID")); vehicle.setPlate(rs.getString("PLATE")); vehicle.setChassis(rs.getString("CHASSIS")); vehicle.setColor(rs.getString("COLOR")); vehicle.setWheel(rs.getInt("WHEEL")); vehicle.setSeat(rs.getInt("SEAT")); } }); return vehicle; }
package org.ourpioneer.vehicle.jt; import java.sql.ResultSet; import java.sql.SQLException; import org.ourpioneer.vehicle.bean.Vehicle; import org.springframework.jdbc.core.RowMapper; public class VehicleRowMapper implements RowMapper<Vehicl