編輯:關於 Android 程式設計
Spring JDBC 是 Spring 提供的持久層技術,目的是降低直接使用 JDBC API 的門檻,以更直接、更簡潔的方式操作資料庫。其核心是 JdbcTemplate,能大幅減少樣板程式碼。
以下 DAO 示範了建立表、新增、取得主鍵、批量更新、查詢與呼叫預存程序等常見操作:
@Repository
public class ViewSpaceDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void initDb() {
String sql = "create table t_user_2(user_id int primary key,user_name varchar(60))";
jdbcTemplate.execute(sql);
}
// 基本新增
public void updateJdbc1() {
final String sql = "INSERT INTO t_user(user_name,password) VALUES(?,?)";
Object[] params = new Object[]{"MonkeyKing","孫悟空"};
jdbcTemplate.update(sql, params);
}
// 帶入參數型別的新增
public void updateJdbc2() {
final String sql = "INSERT INTO t_user(user_name,password) VALUES(?,?)";
Object[] params = new Object[]{"MonkeyKing","孫悟空"};
jdbcTemplate.update(sql, params, new int[]{Types.VARCHAR, Types.VARCHAR});
}
// 取得主鍵的更新
public void updateJdbc3() {
final String sql = "INSERT INTO t_user(user_name,password) VALUES(?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection arg0)
throws SQLException {
PreparedStatement ps = arg0.prepareStatement(sql);
ps.setString(1, "MonkeyKing");
ps.setString(2, "孫悟空");
return ps;
}
}, keyHolder);
System.out.println(keyHolder.getKey().intValue()); // 印出主鍵
}
// 批量更新
public void batchUpdateSql(final List<User> users) {
final String sql = "INSERT INTO t_user(user_name,password) VALUES(?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement arg0, int arg1) throws SQLException {
User user = users.get(arg1);
arg0.setString(1, user.getUserName());
arg0.setString(2, user.getPassword());
}
@Override
public int getBatchSize() {
return users.size();
}
});
}
// 以 RowCallbackHandler 查詢單筆
public User getDataSql(final int userId) {
String sql = "SELECT user_name,password from t_user where user_id=?";
final User user = new User();
jdbcTemplate.query(sql, new Object[]{userId}, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
user.setUserId(userId);
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
}
});
return user;
}
// 以 RowMapper 處理結果集
public List<User> getUserById(final int startId, final int endId) {
String sql = " SELECT user_name,password from t_user where user_id between ? and ?";
return jdbcTemplate.query(sql, new Object[]{startId, endId}, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
return user;
}
});
}
// 以 CallableStatementCallback 呼叫預存程序
public int getUserNum(final int userId) {
String sql = "{call P_GET_USER(?,?)}";
Integer num = jdbcTemplate.execute(sql, new CallableStatementCallback<Integer>() {
@Override
public Integer doInCallableStatement(CallableStatement cs)
throws SQLException, DataAccessException {
cs.setInt(1, userId); // 綁定入參
cs.registerOutParameter(2, Types.INTEGER); // 註冊輸出參數
cs.execute();
return cs.getInt(2); // 取得輸出值
}
});
return num;
}
}
需在設定檔中啟用註解掃描、定義資料來源、JdbcTemplate、交易管理器,並透過 AOP 為 Service 層加入交易增強:
<!-- 掃描並注入標註了 Spring 註解的類 -->
<context:component-scan base-package="com.smart.dao"/>
<!-- DBCP 資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/sampledb"
p:username="root"
p:password=""/>
<!-- JdbcTemplate,注入 dataSource -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"/>
<!-- 交易管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<!-- 透過 AOP 為 Service 層加入交易 -->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.techman.service..*(..))" id="serviceMethod"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name=""/>
</tx:attributes>
</tx:advice>
對於圖片、長文字等大物件,Spring 透過 LobHandler 與 LobCreator 處理:
@Repository
public class ViewPointDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private LobHandler lobHandler;
@Autowired
private DataFieldMaxValueIncrementer incre;
// 寫入 Lob 欄位
public void addViewPoint(final ViewPoint viewPoint) {
String sql = "INSERT INTO t_view_point(point_id,space_id,point_name,ticket_price,img_file,description) VALUES(?,?,?,?,?,?)";
jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) {
@Override
protected void setValues(PreparedStatement ps, LobCreator lobCreator)
throws SQLException, DataAccessException {
ps.setInt(1, incre.nextIntValue());
ps.setInt(2, viewPoint.getSpaceId());
ps.setString(3, viewPoint.getPointName());
ps.setDouble(4, viewPoint.getTicketPrice());
lobCreator.setBlobAsBytes(ps, 5, viewPoint.getImgFile()); // Blob
lobCreator.setClobAsString(ps, 6, viewPoint.getDescription()); // Clob
}
});
}
// 以位元組方式讀取 Blob
public List<ViewPoint> getImgFiles(final int spaceId) {
String sql = "SELECT point_id,img_file FROM t_view_point WHERE point_id=? and img_file is not null";
return jdbcTemplate.query(sql, new Object[]{spaceId}, new RowMapper<ViewPoint>() {
@Override
public ViewPoint mapRow(ResultSet rs, int rowNum) throws SQLException {
int pointId = rs.getInt(1);
byte[] attach = lobHandler.getBlobAsBytes(rs, 2);
ViewPoint viewPoint = new ViewPoint();
viewPoint.setPointId(pointId);
viewPoint.setImgFile(attach);
return viewPoint;
}
});
}
// 以串流方式讀取 Blob
public void getImgFile(final int pointId, final OutputStream os) {
String sql = " SELECT img_file FROM t_view_point where point_id=? ";
jdbcTemplate.query(sql, new Object[]{pointId}, new AbstractLobStreamingResultSetExtractor() {
protected void handleNoRowFound() throws LobRetrievalFailureException {
System.out.println("Not Found Result!");
}
@Override
protected void streamData(ResultSet arg0) throws SQLException, IOException, DataAccessException {
InputStream is = lobHandler.getBlobAsBinaryStream(arg0, 1);
if (is != null) {
FileCopyUtils.copy(is, os);
}
}
});
}
}
整體而言,Spring JDBC 透過 Callback 與 RowMapper 等設計,讓開發者能把心力集中在 SQL 與結果映射上,省去大量釋放資源的樣板程式,是企業應用持久層的實用選擇。
Android RadioGroup 單選組用法實例詳解
本文以實例講解 Android 中 RadioGroup 的用法,供需要的朋友參考。 RadioGroup 在需要「多選一」的情境下非常好用,它能將多個 RadioBut
Android 通知機制完整教學:從基本發送到 PendingIntent 點擊與音效震動
通知(Notification)是 Android 相當有特色的一項設計。當應用程式想提醒使用者某件事,而自己又不在前景執行時,通知就是最合適的管道:發出後,手機最上方的
Android 知識梳理:屏幕適配完整攻略
Android 的碎片化問題困擾著幾乎所有開發者,其中屏幕適配是最頭疼的一塊。想讓 App 在成千上萬種設備上都有體面的顯示效果,適配必須做到位。本文結合官方文檔與個人實
自訂 ProgressBar:任何圖片都能變成轉圈動畫
今天群裡有人問怎麼自訂 Android Holo 主題下的 ProgressBar。剛好我之前做過類似的事——透過自寫動畫加上自訂 Style,可以用任何一張圖片當作 P