《Spring編程技術與應用》課件4_第1頁
《Spring編程技術與應用》課件4_第2頁
《Spring編程技術與應用》課件4_第3頁
《Spring編程技術與應用》課件4_第4頁
《Spring編程技術與應用》課件4_第5頁
已閱讀5頁,還剩16頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

4.1.1連接數(shù)據庫

Spring的JDBC抽象框架提供了一系列接口和類實現(xiàn)對數(shù)據源的連接。DataSourceUtils類:提供從JNDI獲取連接.方法getDataSourceFromJndi用以針對那些不使用BeanFactory或者ApplicationContext的應用。通過DataSourceUtils.getConnection(DataSource)可取得JDBC連接。SmartDataSource接口:提供與關系數(shù)據庫的連接,它繼承javax.sql.DataSource接口,它在數(shù)據庫操作后可智能決定是否需要關閉連接。對于需要重用一個連接的應用可提高效率。DriverManagerDataSource類:實現(xiàn)SmartDataSource接口,通過bean的屬性配置完成JDBC驅動,并每次都返回一個新的連接。(1)連接Access數(shù)據庫的配置<beanid="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource"><propertyname="driverClassName"value="sun.jdbc.odbc.JdbcOdbcDriver"/><propertyname="url"value="jdbc:odbc:driver={MicrosoftAccessDriver(*.mdb)};DBQ=f:/data.mdb"/></bean>(2)基于屬性文件連接Mysql數(shù)據庫的配置<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="locations"value="/WEB-INF/conf/perties"/></bean><beanid="dataSource"class="mons.dbcp.BasicDataSource"><propertyname="driverClassName"value="${jdbc.driverClassName}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></bean>4.1.2數(shù)據源的注入packagechapter4;importorg.springframework.jdbc.core.JdbcTemplate;publicclassUserDaoImplimplementsUserDao{ privateJdbcTemplatejdbcTemplate; publicJdbcTemplategetJdbcTemplate(){ returnjdbcTemplate; } publicvoidsetJdbcTemplate(JdbcTemplatejdbcTemplate){ this.jdbcTemplate=jdbcTemplate; }

……//其他業(yè)務邏輯方法}3.配置文件(beans.xml)<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns...><beanid="dataSource"....數(shù)據源</bean> <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"> <propertyname="dataSource"> <reflocal="dataSource"/> </property> </bean> <beanid="userDAO"class="chapter4.UserDaoImpl"> <propertyname="jdbcTemplate"> <reflocal="jdbcTemplate"/> </property> </bean>......</beans>編程中也可以采用非注入方式來設置數(shù)據源管理對象以下程序中直接通過對象的setter方法實現(xiàn)數(shù)據源的設置。DriverManagerDataSourcedataSource=newDriverManagerDataSource();dataSource.setDriverClassName("sun.jdbc.odbc.JdbcOdbcDriver"); dataSource.setUrl("jdbc:odbc:xx");//假設xx為ODBC數(shù)據源 UserDaouserDAO=newUserDao(); userDAO.setJdbcTemplate(newJdbcTemplate(dataSource));4.1.3使用JdbcTemplate查詢數(shù)據庫1.使用queryForList方法將多行記錄存儲到列表中

Stringsql="SELECT*FROM欄目";

List<Map<String,Object>>x=jdbcTemplate.queryForList(sql);要訪問第1行的欄目標題可以用 x.get(0).get("title")。2.通過query方法執(zhí)行SQL語句,對多行查詢結果進行對象封裝

--(1)使用RowMapper數(shù)據記錄映射接口通過回調RowMapper接口的mapRow方法可處理結果集的每行。并且每行處理后可返回一個對象,所有行返回的對象形成對象列表集合。publicList<Column>getAll(){List<Column>

rows

=

jdbcTemplate.query(“SELECT*FROM欄目”,newRowMapper<Column>(){ publicColumnmapRow(ResultSetrs,introwNum)throwsSQLException{Columnm=newColumn();//創(chuàng)建欄目對象

m.setTitle(rs.getString(“title”));//根據獲取記錄字段值設置欄目屬性m.setNumber(rs.getInt(“id”));

returnm;//返回一行的處理結果});returnrows;//所有行的處理結果}(2)使用RowCallbackHandler數(shù)據記錄回調管理器接口RowCallbackHandler接口定義的processRow方法將對結果集的每行分別進行處理,但方法無返回值。

publicstaticList<String>getName(Stringtable){ Stringsql="selectdistinctnamefrom"+table;finalList<String>result=newList<String>();//存放結果 jdbcTemplate.query(sql,newRowCallbackHandler(){ publicvoidprocessRow(ResultSetrs)throwsSQLException{ result.add(rs.getString("name"));//加入結果集 } });returnresult;}3.返回單值結果的查詢方法有一些查詢方法用來執(zhí)行返回單個值。例如:queryForInt,queryForLong或者queryForObject。publicbooleanlogincheck(Stringloginname,Stringpass){ Stringsql="Selectcount(*)fromuserwhereloginname='"+loginname +"'andpassword='"+pass+"'"; returnjdbcTemplate.queryForInt(sql)>0;}

queryForObject方法queryForObject方法將會把返回的JDBC類型轉換成最后一個參數(shù)所指定的Java類。如果類型轉換無效,那么將會拋出InvalidDataAccessApiUsageException異常。如果無查詢結果,會拋出EmptyResultDataAccessException異常。例如:String

name

=

(String)

jdbcTemplate.queryForObject("SELECT

name

FROM

USER

WHERE

user_id

=

?",

new

Object[]

{“123”},String.class);

//帶填充參數(shù)情形

如果不含SQL填充參數(shù),可以用如下形式:Stringname=(String)jdbcTemplate.queryForObject("SELECT

name

FROM

USER

WHERE

user_id

=’123’",String.class);實際上,queryForInt(sql)可用queryForObject(sql,Integer.class)來代替。4.1.4使用JdbcTemplate更新數(shù)據庫1.完整SQL命令串的執(zhí)行處理如果SQL拼寫完整,則可采用只有一個SQL命令串參數(shù)的update方法或execute方法。

Stringsql="INSERTINTO欄目(title)"+"VALUES('"+title1+"')";

jdbcTemplate.execute(sql);2.帶填充參數(shù)的SQL語句的執(zhí)行處理(1)通過參數(shù)數(shù)組填充SQL語句中的內容Stringsql="insertintouservalues(?,?,?,?,10)";Object[]params=newObject[]{loginname,password,emailAddress,

username};jdbcTemplate.update(sql,params);(2)利用PreparedStatementSetter接口處理預編譯SQL

publicvoidaddScore(finalStringloginname,finalints){

Stringsql="updateusersetscore=score+?whereloginname=?"; jdbcTemplate.update(sql,newPreparedStatementSetter(){ publicvoidsetValues(PreparedStatementps)throwsSQLException{ ps.setInt(1,s);

ps.setString(2,loginname); } });}4.1.5對業(yè)務邏輯的應用測試【程序清單4-6】文件名為TestJDBCTemplate.java....ApplicationContextapplicationContext=newClassPathXmlApplicationContext("/beans.xml");UserDaouserDAO=applicationContext.getBean("userDAO", UserDaoImpl.class);if(userDAO.register("123","xxxxxx","mary@","mary")){ System.out.println("auserregistered"); userDAO.addScore("123",5); System.out.println(userDAO.getScore("123")); } }}4.2數(shù)據庫中大容量字節(jié)數(shù)據的讀寫訪問4.2.1將大容量數(shù)據寫入數(shù)據庫Spring定義了LobCreator接口,以統(tǒng)一的方式操作各種數(shù)據庫的LOB類型數(shù)據。LobCreator接口中的方法:voidsetBlobAsBinaryStream(PreparedStatementps,intparamIndex,InputStreamcontentStream,intcontentLength):通過流填充BLOB數(shù)據;voidsetBlobAsBytes(PreparedStatementps,intparamIndex,byte[]content):通過二進制數(shù)據填充BLOB數(shù)據;voidsetClobAsAsciiStream(PreparedStatementps,intparamIndex,InputStreamasciiStream,intcontentLength):通過Ascii字符流填充CLOB數(shù)據;voidsetClobAsCharacterStream(PreparedStatementps,intparamIndex,ReadercharacterStream,intcontentLength):通過Unicode字符流填充CLOB數(shù)據;voidsetClobAsString(PreparedStatementps,intparamIndex,Stringcontent):通過字符串填充CLOB數(shù)據。

為實現(xiàn)大容量數(shù)據寫入,JdbcTemplate提供了如下方法:

execute(Stringsql,AbstractLobCreatingPreparedStatementCallbacklcpsc)【程序清單4-8】將文件存儲到數(shù)據庫中publicvoidsave(Stringfilepath)throwsFileNotFoundException{ finalFilex=newFile(filepath); finalStringfilename=x.getName();finalInputStreamis=newFileInputStream(x); finalLobHandlerlobHandler=newDefaultLobHandler();//創(chuàng)建LobHandler對象

jdbcTemplate.execute("insertintofilesave(filename,content)values(?,?)", newAbstractLobCreatingPreparedStatementCallback(lobHandler){ @Override protectedvoidsetValues(PreparedStatementpstmt,LobCreatorlobCreator)

throwsSQLException,DataAccessException{ pstmt.setString(1,filename); lobCreator.setBlobAsBinaryStream(pstmt,2,is,(int)x.length());}});}4.2.2從數(shù)據庫讀取大容量數(shù)據

LobHandler接口常用方法如下:InputStreamgetBlobAsBinaryStream(ResultSetrs,intcolumnIndex):從結果集中返回InputStream,通過InputStream讀取BLOB數(shù)據;byte[]getBlobAsBytes(ResultSetrs,intcolumnIndex):以二進制數(shù)據的方式獲取結果集中的BLOB數(shù)據;InputStreamgetClobAsAsciiStream(ResultSetrs,intcolumnIndex):從結果集中返回InputStream,通過InputStreamn以Ascii字符流方式讀取BLOB數(shù)據;ReadergetClobAsCharacterStream(ResultSetrs,intcolumnIndex):從結果集中獲取Unicode字符流Reader,并通過Reader以Unicode字符流方式讀取CLOB數(shù)據;StringgetClobAsString(ResultSetrs,intcolumnIndex):從結果集中以字符串的方式獲取CLOB數(shù)據

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論