之前的時候寫過一篇關於mybatis插件--mybatis plus的文章:
我自己的博客平臺發佈之後,有小粉絲跟我說,現在剛開始學習Java,是不是可以不用學mybatis了直接學這個啊,聽得我心裏一陣後怕,總感覺自己帶偏了他們的想法
其實我個人覺得,這不僅僅是他這種初學者,也是很多人的錯誤想法,就是覺得新的技術就是好的,不信?看這個,這也是一個初學者,在寫代碼的過程中遇到這樣一個問題
原因,我直接上聊天記錄吧
怎麼樣,這個問題簡單嗎?但是也凸顯了一個問題,學習,尤其是開發這一行,真的不能激進,所以我藉着今天的這個引子,整理今天的這份文章--mybatis,從最一開始的mybatis入門直到整合spring,並且附代碼實現,剛開始學習的朋友可以實際操作一下,老牌程序員可以回顧一下當年的青蔥歲月,哈哈哈哈哈
我們來看今天的正題吧
MyBatis前世
原生JDBC操作數據庫的流程
加載驅動
獲取鏈接 connection
獲取statement
設置sql
給佔位符 set值
執行sql,獲取結果集
對結果集進行解析、封裝
釋放資源
原生的jdbc操作數據庫的缺點:
頻繁地進行獲取鏈接、關閉鏈接,資源浪費。 數據庫連接池
sql語句屬於硬編碼,維護不方便。並且需求變得可能性大,要經常地修改sql
佔位符設置參數也屬於硬編碼,維護不方便
結果集解析過程也是硬編碼,希望是能夠自動地封裝成我們自己開發的pojo對象中去
mybatis入門
mybatis 是一個持久層框架 ORM,他可以對jdbc的操作過程進行封裝,使開發者只需關注sql本身,而無需去處理 註冊驅動、獲取鏈接、獲取statement、結果集解析、資源釋放等工作。
ORM :Object Ralational Mapping 對象關係映射
簡單地說,是通過描述
對象和關係數據庫之間的元數據的映射關係,將java中的對象持久化到關係數據庫中。
mybatis配置
1、全局配置文件mybatis.xml(名字任意)
配置mybatis的運行環境,包括連接池、事務等。
2、配置映射文件(配置sql)mapper.xml
3、SqlSessionFactory(會話工廠,通過配置文件獲取的)
創建SqlSession。
4、SqlSession(會話)
操作數據庫。
5、Executor(執行器)
sqlSession是通過執行器來操作數據庫的。
6、mapped Statement(底層封裝對象)
對數據庫的操作進行封裝,包括sql、輸入參數、輸出結果。
支持的輸入輸出參數類型
java基本類型
hashmap
自定義pojo對象
簡單的Mybatis入門程序
項目架構
jar包
log4j.properties
# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?><!--mybatis的運行環境
mybatis與Spring整合後就不需要了
--><!-- 事務--><!--數據庫連接池-->
Users.java
publicclassUsers {privateStringusername;privateDatebirthday;privateStringsex;privateStringaddress;publicStringgetUsername() {returnusername; }publicvoidsetUsername(Stringusername) {this.username = username; }publicStringgetSex() {returnsex; }publicvoidsetSex(Stringsex) {this.sex = sex; }publicDategetBirthday() {returnbirthday; }publicvoidsetBirthday(Datebirthday) {this.birthday = birthday; }publicStringgetAddress() {returnaddress; }publicvoidsetAddress(Stringaddress) {this.address = address; }}
Users.mapper
<?xml version="1.0" encoding="UTF-8" ?><!--
namespace;命名空間
作用:分割sql
--><!--根據姓名查詢用戶信息--><!--
id用於標識映射文件中的sql,其實是statement的id
parameterType:參數類型
resultType:輸出結果類型,單條結果的類型
#{}:佔位符。如果爲簡單類型,則可以通過#{value}來取值,也可以通過#{任意名字}來取值
-->select * from users where id=#{id}<!--${}字符串拼接,不能防止sql注入-->/*傳參爲‘李%’*/ select * from users where username like #{value} /*傳參爲‘李’*/ /*select * from users where username like '${value}%'*/
UsersTest.java
package com.me.test;importcom.me.pojo.Users;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Before;importorg.junit.Test;importjava.io.IOException;importjava.io.InputStream;importjava.util.List;publicclassUsersTest{privateSqlSessionFactorysqlSessionFactory; @Beforepublicvoidinit()throwsIOException{//獲取全局配置文件InputStreamin=Resources.getResourceAsStream("mybatis.xml");//獲取SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(in); } @Testpublicvoid test()throwsIOException{//獲取sqlSessionSqlSessionsqlSession=sqlSessionFactory.openSession();//執行sqlUsersuser=sqlSession.selectOne("UsersMapper.selectById",1);System.err.println(user.getUsername()); sqlSession.close(); } @Testpublicvoid test2(){SqlSessionsqlSession=sqlSessionFactory.openSession();List usersList=sqlSession.selectList("UsersMapper.selectByUserName","李%");/*List<Users> usersList=sqlSession.selectList("UsersMapper.selectByUserName","李");*/System.err.println(usersList);/*System.out.println(usersList.get(0).getUsername());
System.out.println(usersList.get(1).getUsername());*/}}
mybatis對數據庫的常用操作
一、查詢
select*fromuserswhereid=#{id} /*傳參爲‘李%’*/select*fromuserswhereusername like#{value}/*傳參爲‘李’*//*select * from users where username like '${value}%'*/
測試方法
@TestpublicvoidselectByUserName(){ SqlSession sqlSession=sqlSessionFactory.openSession(); List usersList=sqlSession.selectList("UsersMapper.selectByUserName","李%");/*List<Users> usersList=sqlSession.selectList("UsersMapper.selectByUserName","李");*/System.err.println(usersList);/*System.out.println(usersList.get(0).getUsername());
System.out.println(usersList.get(1).getUsername());*/}
二、新增
<!--添加用戶信息-->insert into users(id,username,password,address,birthday,sex) values(#{id},#{username}, # {password},#{address},#{birthday},#{sex})insert into users(id,username,password,address,birthday,sex) values(#{id},#{username},# {password},#{address},#{birthday},#{sex})
測試方法
@TestpublicvoidaddUser(){ SqlSession sqlSession=sqlSessionFactory.openSession(); Users users=newUsers(4,"王五","123",newDate(),"男","北京");intres=sqlSession.insert("UsersMapper.addUser",users); sqlSession.commit(); sqlSession.close(); }@TestpublicvoidaddUser2(){ SqlSession sqlSession=sqlSessionFactory.openSession(); Users user=newUsers(5,"王五","123",newDate(),"男","北京");intres=sqlSession.insert("UsersMapper.addUser",user); System.err.println("res:"+res); System.err.println("users.getId:"+user.getId()); sqlSession.commit(); sqlSession.close(); }
三、修改
update userssetpassword=#{password},address=#{address} where id=#{id}
測試方法
@TestpublicvoidupdateUser(){ SqlSession sqlSession=sqlSessionFactory.openSession(); Users user=newUsers(); user.setPassword("newPass123456"); user.setAddress("濟南"); user.setId(4);intres=sqlSession.update("UsersMapper.updateUser",user); sqlSession.commit(); sqlSession.close(); }
四、刪除
/*這裏是簡單類型,# { value } 中的value可以任意寫*/deletefrom users where id=#{id}
測試方法
@TestpublicvoiddeleteUser(){ SqlSession sqlSession=sqlSessionFactory.openSession();intres=sqlSession.delete("UsersMapper.deleteUser",5); System.err.println("res:"+res); sqlSession.commit(); sqlSession.close(); }
mybatis.xml的一些配置項
1、加載外部資源文件
2、起別名
<!--
起別名第一種方式
type:給哪個類起別名 alias:別名
--><!--<typeAlias type="com.me.pojo.Users" alias="user"></typeAlias>--><!--
起別名第二種方式:批量起別名
name:包,起的別名就是類名的全名,首字母大寫、小寫皆可
-->
3、SqlSessionFactory和SqlSession
//獲取全局配置文件InputStream in= Resources.getResourceAsStream("mybatis.xml");//獲取SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(in);//獲取sqlSessionqlSession sqlSession=sqlSessionFactory.openSession();//執行sql
SqlSessionFactory:它是通過全局配置文件獲取的,SqlSessionFactoryBuilder創建的。一旦它被創建,就會在程序的執行期一直存在,因此只需要一個實例。也就是說希望它是單例的。
SqlSession:作用是操作數據庫,是線程不安全的。因而希望每個線程都有自己的sqlSession的實例。
4、工具類
package com.me.utils;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importjava.io.IOException;importjava.io.InputStream;publicclassMybatisUtils{privatestaticSqlSessionFactorysqlSessionFactory;static{try{//獲取全局配置文件InputStreamin=Resources.getResourceAsStream("mybatis.xml");//獲取SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(in); }catch(IOExceptione) { e.printStackTrace(); } }publicstaticSqlSessionFactorygetSqlSessionFactory(){returnsqlSessionFactory; }}
5、測試類
@TestpublicvoidselectById()throwsIOException{//獲取sqlSessionSqlSession sqlSession= MybatisUtils.getSqlSessionFactory().openSession();//執行sqlUsers user=sqlSession.selectOne("UsersMapper.selectById",1); System.err.println(user.getUsername()); sqlSession.close(); }
Spring與Mybatis整合
mybatis:dao層,操作數據庫,需要單例的SqlSessionFactory工廠。
spring:容器,管理對象。
可以將SqlSessionFactory、事務、連接池以及mapper的動態代理交給spring來做。
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/spring-aop.xsd"><!--加載外部資源文件--><!--數據庫連接池--><!--配置SqlSessionFactory,通過Spring來管理會話工廠--><!--配置數據源:因爲要使用SqlSession操作數據庫--><!--加載mybatis的全局配置文件--><!--<property name="configLocation" value="classpath:mybatis.xml"></property>--><!--Spring起別名--><!--mapper動態代理 通過掃描批量加載mapper接口來創建代理bean,這些bean的名字是接口名字(首字母小寫)--><!--指定mapper接口的包路徑--><!--註解掃描-->
UsersService.java
publicinterfaceUsersService{publicUsersselectById(intid);}
UsersServiceImpl
@Service("userService")publicclassUsersServiceImplimplementsUsersService{@AutowiredprivateUsersMapper usersMapper;@OverridepublicUsersselectById(intid){returnusersMapper.selectById(id); }}
測試類
publicclassAppTest{@TestpublicvoidselectById(){ ApplicationContext applicationContext=newClassPathXmlApplicationContext("applicationContext.xml"); UsersService usersService= (UsersService) applicationContext.getBean("userService"); Users user=usersService.selectById(1); System.err.println(user.getUsername()); }}
總結
好了,不知道看完今天的內容大家感覺怎麼樣,有沒有收穫,我基本是按照從入門開始,逐步的往裏面填充一些知識的順序將mybatis進行了整理,那這個時候,我想,在實際的學習過程中你肯定還會遇到一些這樣那樣的問題,但是千萬不要突進,腳踏實地,就從一些基礎的,無聊的東西開始一點點的學習,網絡上那些說這個牛,哪個好的,他肯定有一門傍身的技術作爲基礎,所以才能打到他說的那個層次
最後,所有程序員都能當架構師,哈哈哈哈哈