21springmvc視頻教程mybatis電商項目java商城源碼ssm框架教案-day_第1頁
21springmvc視頻教程mybatis電商項目java商城源碼ssm框架教案-day_第2頁
21springmvc視頻教程mybatis電商項目java商城源碼ssm框架教案-day_第3頁
21springmvc視頻教程mybatis電商項目java商城源碼ssm框架教案-day_第4頁
21springmvc視頻教程mybatis電商項目java商城源碼ssm框架教案-day_第5頁
已閱讀5頁,還剩22頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

課程計1、mybatis2、MybatisjdbcMybatisMybatis3、Daodao動態(tài)方1、輸入和輸出輸入?yún)?shù)返回值4、MybatisMyBatis介MyBatis本是apache的一個開源項目iBatis,2010年這個項目由apachesoftwarefoundation遷移到了code,并且改名為MyBatis。2013年11月遷移到。只需要關(guān)注SQL本身,而不需要花費精力去處理例如驅(qū)動、創(chuàng)建connection、創(chuàng)建進(jìn)行生成最終執(zhí)行的sql語句,最后由mybatis框架執(zhí)行sql并將結(jié)果成java對象并mysql先導(dǎo)入創(chuàng)建數(shù)據(jù)庫的sql導(dǎo)入到數(shù)據(jù)庫中eclipsemars1、創(chuàng)建一個java2jarmysqljdbc23jdbcstatement對象4sql語句5sql語句中的參數(shù)(6statementsql7sqljdbcpublicpublicstaticvoidmain(String[]args){Connectionconnection=PreparedStatementpreparedStatement=null;ResultSetresultSet=null;tryconnection=terEncoding=utf-8","root","root");//定義sql?Stringsql="select*fromuserwhereusername=preparedStatement=preparedStatement.setString(1, resultSet=preparedStatement.executeQuery();}}catch(Exceptione){ try}catch(SQLExceptione)//TODOAuto-generatedcatchblock}}try{}catch(SQLExceptione)//TODOAuto-generatedcatchblock}}try{}catch(SQLExceptione)//TODOAuto-generatedcatchblock}}}}上邊使用jdbc的原始方法(封裝)實現(xiàn)了查詢數(shù)據(jù)庫表記錄的操作jdbc2、Sql語句在代碼中硬編碼,造成代碼不易,實際應(yīng)用sql變化的可能較大,sql變動需要改變java代碼。3preparedStatementsqlwhere條件不一定,可能多也可能少,修改sql還要修改代碼,系統(tǒng)不易。4、對結(jié)果集解析存在硬編碼(查詢列名),sql變化導(dǎo)致解析代碼變化,系統(tǒng)不易,pojo對象解析比較方便。Mybatis架Mapper11mybatismapper.xml文件即sql文件,文件中配置了操作數(shù)據(jù)庫的sql語句。此文件需要在SqlMapConfig.xml中加載。5MappedStatementmybatismybatissql信息等。mapper.xmlsqlMappedStatement對象,sqlid即Mappedstatementid。pojoExecutor通過MappedStatement在執(zhí)行sql前將輸入的java對象至sql中,輸入?yún)?shù)就jdbcpreparedStatement設(shè)置參數(shù)。7MappedStatement對sqlHashMappojoExecutor通過MappedStatement在執(zhí)行sql后將輸出結(jié)果至java對象中輸出結(jié)果過Mybatis入門程mybatismybaits的代碼 idjavaeclipse創(chuàng)建java工程,jdk1.7.0_72jar加入mybatis包、依賴包、數(shù)據(jù)驅(qū)動包perties##Globalloggingconfigurationlog4j.rootLogger=DEBUG,stdout#Consoleoutput...log4j.appender.stdout=log4j.appender.stdout.layout=.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p[%t]-mybatislog4j<?xml<?xmlversion="1.0"encoding="UTF-8"<!DOCTYPEPUBLIC"-PUBLIC"-"http://DTDConfig和springenvironments<environments<environment使用jdbc事務(wù)管理<transactionManagertype="JDBC"數(shù)據(jù)庫連接池<dataSource<propertyname="driver"value="com.mysql.jdbc.Driver"/><propertyname="url"tf-8"/><propertyname="username"value="root"<propertyname="password"value="root"第五步:poPublicPublicclassUserprivateintprivateStringusername;/privateStringprivateDatebirthday;/privateStringaddress;/第六步:sql文在classpath下的 下創(chuàng)建sql文件<?xml<?xmlversion="1.0"encoding="UTF-8"<!DOCTYPEPUBLIC"-"<mapper//DTDMapper第七步:加載文mybatis框架需要加載文件,將Users.xml添加在SqlMapConfig.xml,如下<mapperid 根據(jù)id<selectid="findUserById"parameterType="int" select*fromuserwhereid=publicpublicclass{privateSqlSessionFactorypublicvoidcreateSqlSessionFactory()throwsIOExceptionStringresource=//sqlSessionFactory=new}id查詢用戶信息publicvoidtestFindUserById()SqlSessionsqlSession=null;try{創(chuàng)建數(shù)據(jù)庫會話實例sqlSession=查詢單個記錄,根據(jù)用戶idUseruser=}catch(Exceptione){}finallyif(sqlSession!=null){}}}}<select<selectid="findUserByUsername"parameterType="java.lang.String" select*fromuserwhereusernamelikeparameterType:定義輸入到sql中的 resultType:定義結(jié)果類型publicvoidtestFindUserByUsername()SqlSessionsqlSession=null;try{創(chuàng)建數(shù)據(jù)庫會話實例sqlSession=查詢單個記錄,根據(jù)用戶idList<User>list=sqlSession.selectList("test.findUserByUsername張");}catch(Exceptione){}finallyif(sqlSession!=null){}}}#{}和#{}#{}preparedStatementjavajdbc類型轉(zhuǎn)換,#{}sql#{}pojo屬性值。parameterType傳輸單個簡單類型值,#{}value或其它名稱。${}sql串,通過${}parameterTypesql中且不進(jìn)行jdbc類${}pojoparameterType傳輸單個簡單類型值,resultType:指定輸出結(jié)果類型,mybatis將sql查詢結(jié)果的一行記錄數(shù)據(jù)為selectOne(ornull)tobereturnedbyselectOne(),butfound:3<insertid="insertUser"insertintopublicvoidtestInsert()SqlSessionsqlSession=null;try{創(chuàng)建數(shù)據(jù)庫會話實例sqlSession=Useruser=newUser(); }catch(Exceptione){}finallyif(sqlSession!=null){}}}mysql<insertid="insertUser" selectKey<insertid="insertUser" selectKey<selectKeykeyProperty="id"order="AFTER"selectinsertintouser(username,birthday,sex,address)insertselectKeyafterMysqluuidselectuuid()uuid <selectKeyresultType="java.lang.String"order="BEFORE"selectinsertintouser(id,username,birthday,sex,address)<deleteid="deleteUserById"parameterType="int">deletefromuserwhereid=#{id}根據(jù)idpublicvoidtestDelete()SqlSessionsqlSession=null;try{創(chuàng)建數(shù)據(jù)庫會話實例sqlSession=}catch(Exceptione){}finallyif(sqlSession!=null){}}}<updateid="updateUser"updateuserwhere//更新用戶信 publicvoidtestUpdate()SqlSessionsqlSession=null;try{創(chuàng)建數(shù)據(jù)庫會話實例sqlSession=Useruser=newUser(); }catch(Exceptione){}finallyif(sqlSession!=null){}}}Mybatisjdbc2、Sql語句寫在代碼中造成代碼不易,實際應(yīng)用sql變化的可能較大,sql變動需要改java代碼。解決:將Sql語句配置在Xmapper.xml文件中與java代碼分離3sqlsqlwhere條件不一定,可能多也可能少,占位符解決:Mybatis自動將java對象至sql語句,通過statement中的parameterType定4sql變化導(dǎo)致解析代碼變化,且解析前需要遍歷,如果能將數(shù)據(jù)庫pojo對象解析比較方便。解決:Mybatis自動將sql執(zhí)行結(jié)果至java對象,通過statement中的resultTypemybatishibernateMybatishibernateORMMyBatis需要程序員自己編寫SqlmybatisXML或注解方式靈活配置要運行的sqljava對象和sql語句生成最終執(zhí)行的sql,最后將sql執(zhí)行的結(jié)果再生成java對象。靈活度高,非常適合對關(guān)系數(shù)據(jù)模型要求不高的開發(fā),例如互聯(lián)網(wǎng)、企業(yè)運營類軟件等,因為這類需求變化頻繁,一但需求變化要求成果輸出迅速。但是靈活的前提是mybatis無法做到數(shù)據(jù)庫無關(guān)性如果需要實現(xiàn)支持多種數(shù)據(jù)庫的則需要自定義多套sql的學(xué)習(xí)門檻高,要精通門檻更高,而且怎么設(shè)計O/R,在性能和對象模型之間如何權(quán)Hibernate需要具有很強的經(jīng)驗和能力才行。Dao開發(fā)方MybatisDaoDaoMapperidSqlSessionSqlSessionFactoryBuilderSqlSessionSqlSessionFactory生產(chǎn),所以可以SqlSessionFactory是一個接口,接口中定義了openSession的不同重載方法,SqlSessionFactory的最佳使用范圍是整個應(yīng)用運行期間,一旦創(chuàng)建后可以重復(fù)使用,通常以SqlSessionFactory。SqlSessionsqlSessionSqlSession實例。SqlSession的實例不能共享使用,它也是SqlSessionsession=sqlSessionFactory.openSession();try{//SqlSessionsession=sqlSessionFactory.openSession();try{//do}finally}DaoDaoDaoDao<?xml<?xmlversion="1.0"encoding="UTF-8"<!DOCTYPEPUBLIC"- //DTDMapper <mapper根據(jù)id<selectid="findUserById"parameterType="int" select*fromuserwhereid=<insertid="insertUser" <selectKeykeyProperty="id"order="AFTER"selectinsertintouser(username,birthday,sex,address)DaoPublicPublicinterfaceUserDaopublicUsergetUserById(intid)throwspublicvoidinsertUser(Useruser)throws}PublicclassUserDaoImplimplementsUserDaopublicUserDaoImpl(SqlSessionFactory}privateprivateSqlSessionFactorysqlSessionFactory;publicUsergetUserById(intid)throwsException{SqlSessionsession=sqlSessionFactory.openSession();Useruser=null;try數(shù)user=session.selectOne("test.findUserById",1);}}return}PublicvoidinsertUser(Useruser)throwsException{SqlSessionsqlSession=sqlSessionFactory.openSession();try{sqlSession.insert("insertUser",}}}}DaoprivateSqlSessionFactorypublicvoidinit()throwsprivateSqlSessionFactorypublicvoidinit()throwsExceptionSqlSessionFactoryBuildersessionFactoryBuilder=newSqlSessionFactoryBuilder();InputStreaminputStream=Resources.getResourceAsStream("SqlMapConfig.xml");sqlSessionFactory=sessionFactoryBuilder.build(inputStream);}publicvoidtestGetUserById()UserDaouserDao=newUserDaoImpl(sqlSessionFactory);Useruser=userDao.getUserById(22);}}DaoMapper動態(tài)方框架根據(jù)接口定義創(chuàng)建接口的動態(tài)對象,對象的方法體同上邊Dao接口實現(xiàn)類方2Mapper接口方法名和Mapper.xmlstatementid3Mappermapper.xmlsqlparameterType的4Mapper接口方法的輸出參數(shù)類型和mapper.xml中定義的每個sql的resultType的類型相定義mapper文件UserMapper.xml(內(nèi)容同Users.xml),需要修改namespace的值為UserMapper接口路徑。將UserMapper.xml放在classpath下mapper <?xml<?xmlversion="1.0"encoding="UTF-8"<!DOCTYPEPUBLIC"-PUBLIC"-"<mapper//DTDMapper根據(jù)id<selectid="findUserById"parameterType="int" select*fromuserwhereid=<selectid="findUserByUsername"parameterType="java.lang.String" select*fromuserwhereusernamelike<insertid="insertUser" <selectKeykeyProperty="id"order="AFTER"selectinsertintouser(username,birthday,sex,address)*用戶管理PublicinterfaceUserMapperpublicUserfindUserById(intid)throwspublicvoidinsertUser(Useruser)throws}1Mapper接口方法名和Mapper.xmlstatementid2Mapper接口方法的輸入?yún)?shù)類型和mapper.xml中定義的statementparameterType3Mapper接口方法的輸出參數(shù)類型和mapper.xml中定義的statement的resultType的類型<mapperPublicPublicclassUserMapperTestextendsTestCaseprivateSqlSessionFactoryprotectedvoidsetUp()throwsExceptionStringresource=sqlSessionFactory=new}PublicvoidtestFindUserById()throwsExceptionSqlSessionsession= 對UserMapperuserMapper= Useruser=userMapper.findUserById(1);}}publicvoidtestFindUserByUsername()throwsException{SqlSessionsqlSession=sqlSessionFactory.openSession();UserMapperuserMappersqlSession.getMapper(UserMapper.class);List<User>list=userMapper.findUserByUsername("張");}/r

溫馨提示

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

評論

0/150

提交評論