spring對JDBC的支援

2021-09-21 04:28:54 字數 2841 閱讀 1849

從來沒使用過,感覺還是很有意思的,有工夫可以玩完,呵呵。

spring提供了類org.springframework.jdbc.core.jdbctemplate,它借助配置檔案獲取資料庫資訊,實現了對jdbc開發過程中的載入驅動,建立連線,執行sql語句,對事務進行處理以及一些資料型別轉化等操作的封裝。只需要程式設計師對其傳入sql語句和必要的引數即可輕鬆進行jdbc程式設計。

dao類:

public

class studentdaojdbcimpl 

implements studentdao  

@override 

public

void deletebyid(integer id) ;

// 陣列元素依次對應sql語句中的? 

template.update(sql, args);

// 只需傳sql語句和引數陣列,template會自動載入驅動,建立鏈結,執行sql語句,並且進行事務處理 

@override 

public

void insert(student s) ;

//template會對date型別資料進行轉化 

template.update(sql, args); 

@override 

public student querybyid(integer id) ; 

final student s = 

new student(); 

template.query(sql, args, 

new rowcallbackhandler()  

}); 

if (s.getid() == 

null)  

else  

@override 

public listqueryall()  

}); 

return ret; 

}

配置:

<

beans

>

<

bean

id="datasource"

class

="org.apache.commons.dbcp.basicdatasource"

>

<

property

name

="driverclassname"

>

<

value

>oracle.jdbc.driver.oracledriver

value

>

property

>

<

property

name

="url"

>

<

value

>jdbc:oracle:thin:@localhost:1521:orcl10

value

>

property

>

<

property

name

="username"

>

<

value

>scott

value

>

property

>

<

property

name

="password"

>

<

value

>yf123

value

>

property

>

bean

>

<

bean

id="jdbctemplate"

class

="org.springframework.jdbc.core.jdbctemplate"

>

<

property

name

="datasource"

>

<

reflocal

="datasource"

/>

property

>

bean

>

<

bean

id="dao"

class

="com.yangfei.spring.jdbc.dao.studentdaojdbcimpl"

>

<

property

name

="template"

>

<

reflocal

="jdbctemplate"

/>

property

>

bean

>

beans

>

測試:

public

static

void main(string args) { 

"jdbc.xml"); 

studentdao dao=(studentdao)ctx.getbean(

"dao"); 

system.out.println(dao.querybyid(2)); 

student s=

new student(); 

s.setname(

"xiaozhang"); 

s.setbirthday(

newdate()); 

dao.insert(s);

spring對JDBC的支援

spring提供了對dao層統一異常的處理 spring提供了一些抽象類來支援對dao的編寫 減少了對jdbc編寫的 量 spring用一種方式使用各種資料訪問技術 如 hibernate jdbc mybatis等 需要相關jar包 spring core 3.2.8.release.jar sp...

Spring對JDBC的支援

jdbctemplate類是spring對jdbc支援庫類中的核心類 jdbctemplate負責建立和釋放資源 執行sql語句.儲存過程.並且通過resultset返回資料 string sql update student set stuno name where id object obj n...

Spring對JDBC的支援

專案結構 建立book類 public class book public void setid integer id public string getbookname public void setbookname string bookname public string getauthor ...