JDBC學習之路(十二)使用Spring中的JdbcTemple實現資料查詢
阿新 • • 發佈:2018-12-21
其實在Spring這個框架中,提供了一些對JDBC訪問資料庫的封裝,其中JdbcTemplate就是一個很好用的類,下面來
演示一下這個類的一些用法。首先需要匯入commons-logging.jar,和spring.jar這兩個包。然後使用他的功能就可以了,
可以說,Spring框架對JDBC的封裝是非常強大的,只需要一個數據源,建立完成連線後,對於連線的處理,連線池的
建立和維護,語句的傳送和大資料的訪問和返回,都提供了最好的支援,程式設計師不需要去關注這些,使用極為方便
package com.bird.jdbc.spring;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import com.bird.jdbc.Temple;import com.bird.jdbc.domain.User;public class JdbcTemple { /** * @param args */ public static void main (String[] args) { System.out.println(test2(227)); } public static User test(String name){ JdbcTemplate jdbc = new JdbcTemplate(Temple.getDataSource()); String sql = "select id,name,money,birthday from user where id=?"; Object[] args = new Object[] {name}; Object use = jdbc.queryForObject(sql, args,new RowMapper(){ @Override public Object mapRow(ResultSet rs, int arg1) throws SQLException { User use = new User(); use.setId(rs.getInt("id")); use.setBirthday(rs.getDate("birthday")); use.setMoney(rs.getFloat("money")); use.setName(rs.getString("name")); return use; } }); return (User)use; } /** * 使用反射的基本行對映器 * @param name * @return */ public static User test1(String name){ JdbcTemplate jdbc = new JdbcTemplate(Temple.getDataSource()); String sql = "select id,name,money,birthday from user where id=?"; Object[] args = new Object[] {name}; Object use = jdbc.queryForObject(sql, args,new BeanPropertyRowMapper(User.class)); return (User)use; } /** * 查詢返回多個結果 * @param id * @return */ public static List<User> test2(int id){ JdbcTemplate jdbc = new JdbcTemplate(Temple.getDataSource()); String sql = "select id,name,money,birthday from user where id<?"; Object[] args = new Object[] {id}; @SuppressWarnings("unchecked") List<User> use = jdbc.query(sql, args,new BeanPropertyRowMapper(User.class)); return use; }}
首先提供一個數據源,用來提供資料庫的資訊來進行連線,然後就是行對映器,來對返回的資料進行不同方式的封裝
第一個是使用匿名內部類實現的,對於資料的訪問,spring可以返回一個數據一組資料或者是一個容器,都是可以的
靈活實現,而且只要引數的順序和問號的順序要是一致,其他的就無所謂了,如果不想實現行對映器,也可以使用反
射機制,直接給他一個class檔案就行了。