當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring集成Mybatis plus
生活随笔
收集整理的這篇文章主要介紹了
Spring集成Mybatis plus
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Springboot中流行的持久層框架是Hibernate和Mybatis
前者已經成為Spring Data的規范,以極簡和全自動的對象映射著稱,后者是一個半自動化的ORM框架,SQL獨立存放在XML文件中,提高自由度的同時也方便DBA進行校對和后續SQL優化
由于Mybatis plus完全基于Mybatis,且吸收了一部分HIbernate的優點,提供集成的CRUD,基本上現在開發中都使用Mybatis Plus替代原生Mybatis框架
敲黑板: MybatisPlus 不能和 Mybatis同時使用
使用流程(三步走)
- 實體entity
- Dao層接口Mapper
- Xml文件中的Sql語句
第一步 添加Maven依賴
<dependency><groupId>com.baomidou</groupId><artifactId>mybatisplus-spring-boot-starter</artifactId> </dependency> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId> </dependency> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId> </dependency> 復制代碼第二步 在application.yml中配置Mybatis Plus
使用properties配置文件的可以在www.toyaml.com/index.html進行yml文件的轉換
重點!!!
第一行的xml文件掃描,此處的xml文件存放在resource下的mapper路徑下(我的路徑是resource/mapper/xx模塊/xxx.xml)
第二行的實體掃描!!!要根據自己的entity目錄進行配置 自己根據自己的實體類路徑修改typeAliasesPackage,或者使用我的這種模塊化工程路徑(工程根目錄/modules/xx模塊/entity/xxx.class)
沒添加mysq數據源的再添加如下配置
spring: datasource: continue-on-error: false driver-class-name: com.mysql.jdbc.Driver username: root ##根據自己MySQL的用戶名修改 url: jdbc:mysql://127.0.0.1:3306/renren_test ##根據自己MySQL的ip和端口修改 password: root ##根據自己MySQL的密碼修改復制代碼第三步 進入正題
之前的步驟都是Mybatis的配置和管理,以下才是真正的業務代碼
之前用過JPA的可能直接運行發現并沒有在數據庫中建表,因為Mybatis不支持自動根據實體類創建表,所以需要自己建表,如果要引入這個功能可以引入JPA,只利用JPA的自動建表功能,本文為了簡單明了不涉及,可以查看我另一篇文章Mybatis加入JPA的自動建表功能
Mybatis框架的文件引入方式:
- entity通過第二步的配置typeAliasesPackage進行查找,也可以通過注解方式查找
- Mybatis的xml與mapper對應,mapper提供java層的接口,xml保存相對應的sql語句
- xml在第二步的配置中由Mybatis發現,相對應的Mapper文件在xml中通過namespace的方式關聯
最后一步 測試
在Controller文件中實現Restful接口 SwordController.class
public SwordController { // 自動注入mapperprivate SwordMapper swordMapper;("sword")public sword(UserEntity userEntity) {Sword sword1 = new Sword();sword1.setName("這是一把劍");Sword sword = swordMapper.selectSword("1");return sword;} } 復制代碼訪問127.0.0.1:8080/demo/sword
大功告成!
后記
在其他的博客中大家可能看到,有很多利用sqlsession或者SqlSessionFactoryBean來加載Mybatis配置文件,我這里又沒有sqlsession,經常有人會被搞得一頭霧水,這里解釋一下,在原生的mybatis中,sqlsession可以由SqlSessionFactory創建;而在mybatis-spring中則需要通過SqlSessionFactoryBean來創建,并傳入datasource。 像這樣
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation"> <value>classpath:mybatis/mapper.xml</value> </property> <property name="dataSource" ref="dataSource" /> </bean> 復制代碼但是在Springboot中,mybatis-spring-boot支持自動創建并注冊SqlSessionFactoryBean,所以sqlsession的配置并不需要。感謝Springboot.
總結
以上是生活随笔為你收集整理的Spring集成Mybatis plus的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql逻辑备份之mysqldump
- 下一篇: SpringCloud F.RC2 整合