1、由於之前JdbcTemplate的程式需要編寫一堆的RowMapper的對應檔,顯得有些臃腫,最好是根據pojo類和欄位的名稱進行自動的對應, 所以
SimpleJdbcTemplate支援使用Pojo中的屬性進行自動賦值, 文法為':'開頭。public class UserDaoSpringImpl implements UserDao {
private SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(
JdbcUtils.getDataSource());
public void addUser(User user) {
String sql = "insert into user (name, money, birthday) values (:name, :money, :birthday)";
SqlParameterSource param = new BeanPropertySqlParameterSource(user);
KeyHolder keyHolder = new GeneratedKeyHolder();
this.simpleJdbcTemplate.getNamedParameterJdbcOperations().update(sql,
param, keyHolder);
user.setId(keyHolder.getKey().intValue());
}
public void delete(User user) {
String sql = "delete from user where id=?";
this.simpleJdbcTemplate.update(sql, user.getId());
}
public User findUser(String loginName, String password) {
String sql = "select id, name, money, birthday from user where name=?";
return this.simpleJdbcTemplate.queryForObject(sql,
ParameterizedBeanPropertyRowMapper.newInstance(User.class),
loginName);
}
public User getUser(int userId) {
String sql = "select id, name, money, birthday from user where id=?";
return this.simpleJdbcTemplate.queryForObject(sql,
ParameterizedBeanPropertyRowMapper.newInstance(User.class),
userId);
}
public void update(User user) {
String sql = "update user set name=?, birthday=?, money=? where id=? ";
this.simpleJdbcTemplate.update(sql, user.getName(), user.getBirthday(),
user.getMoney(), user.getId());
sql = "update user set name=:name, birthday=:birthday, money=:money where id=:id ";
this.simpleJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(
user));
}
}
其中使用的JdbcUtils擷取資料來源的代碼如下:public final class JdbcUtils {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "";
private static DataSource myDataSource = null;
private JdbcUtils() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
// myDataSource = new MyDataSource2();
Properties prop = new Properties();
// prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");
// prop.setProperty("user", "user");
InputStream is = JdbcUtils.class.getClassLoader()
.getResourceAsStream("dbcpconfig.properties");
prop.load(is);
myDataSource = BasicDataSourceFactory.createDataSource(prop);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static DataSource getDataSource() {
return myDataSource;
}
public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(url, user, password);
return myDataSource.getConnection();
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
// myDataSource.free(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}2、 完成相同映射的類還包括:NamedParameterJdbcTemplate, 它將之前的預留位置‘?’進行了取名,方便程式的閱讀。 不過這樣的SQL不能再資料庫中直接執行,需要有Spring進行轉換。public class NamedJdbcTemplate {
static NamedParameterJdbcTemplate named = new NamedParameterJdbcTemplate(
JdbcUtils.getDataSource());
/**
* @param args
*/
public static void main(String[] args) {
User user = new User();
user.setMoney(10);
user.setId(2);
System.out.println(findUser1(user));
}
static void addUser(User user) {
String sql = "insert into user(name,birthday, money) values (:name,:birthday,:money) ";
SqlParameterSource ps = new BeanPropertySqlParameterSource(user);
KeyHolder keyHolder = new GeneratedKeyHolder();
named.update(sql, ps, keyHolder);
int id = keyHolder.getKey().intValue();
user.setId(id);
Map map = keyHolder.getKeys();
}
static User findUser(User user) {
String sql = "select id, name, money, birthday from user "
+ "where money > :m and id < :id";
Map params = new HashMap();
// params.put("n", user.getName());
params.put("m", user.getMoney());
params.put("id", user.getId());
Object u = named.queryForObject(sql, params, new BeanPropertyRowMapper(
User.class));
return (User) u;
}
static User findUser1(User user) {
String sql = "select id, name, money, birthday from user "
+ "where money > :money and id < :id";
SqlParameterSource ps = new BeanPropertySqlParameterSource(user);
Object u = named.queryForObject(sql, ps, new BeanPropertyRowMapper(User.class));
return (User) u;
}
}
【注意】1、BeanPropertyRowMapper完成了對象到資料庫欄位的映射關係, 可以不再使用RowMapper來一一對應起來。如果RowMapper只使用1次,則可以直接使用內部類來完成,而不再需要專門的寫一個類。2、KeyHolder, 其中儲存了資料庫中操作的主鍵,取得操作的主鍵後, 方便對進行操作的記錄進行其他動作。 總之:利用反射技術,減少的了不必要的rowmapper,提高了效率 轉自:http://tianya23.blog.51cto.com/1081650/375823