springboot与mybatis整合
重點:
0、回顧
1、修改SpringBoot的數據源Druid
2、配置Mybatis
3、配置PageHelper分頁插件
重點解析:
0、回顧:
thymeleaf
基于html開發
導入pom依賴
application.yul配置是否使用緩存
html開發的相關指令
th:each=“xxx : ${users}”
th:text ${xxx。attr}
th:value
File–>New–>Project…
Spring Initializr
Maven Project
Web
Web
Core
Lombok
Aspects
DevTools
SQL
mybatis+jdbc+mysql
1.修改SpringBoot的數據源Druid(默認數據源是org.apache.tomcat.jdbc.pool.DataSource)
1.1 項目地址
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
1.2 引入依賴
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency>1.3 配置application.yml
application.yml和application.properties區別?
yml文件的好處,天然的樹狀結構,一目了然,實質上跟properties是差不多的。
配置application.yml文件注意事項:
1.4 啟動SpringBoot項目訪問druid
http://localhost:tomcat端口號/項目名稱/druid/
2.配置Mybatis
2.1 引入依賴
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency>MyBatis-Spring-Boot-Starter依賴將會提供如下:
?2) 將創建并注冊SqlSessionFactory的實例,該實例使用SqlSessionFactoryBean將該DataSource作為輸入進行傳遞。
?3) 將創建并注冊從SqlSessionFactory中獲取的SqlSessionTemplate的實例。
?4) 自動掃描您的mappers,將它們鏈接到SqlSessionTemplate并將其注冊到Spring上下文,以便將它們注入到您的bean中。
就是說,使用了該Starter之后,只需要定義一個DataSource即可(application.properties或application.yml中可配置),它會自動創建使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。會自動掃描你的Mappers,連接到SqlSessionTemplate,并注冊到Spring上下文中。
2.2 配置application.yml
mybatis:
#配置SQL映射文件路徑
mapper-locations: classpath:mapper/*.xml
#配置別名
type-aliases-package: com.zking.項目名.model
2.3 使用Mybatis-Generator插件生成代碼
2.3.1 導入并修改generatorConfig.xml和jdbc.properties(resources下)
2.3.2 配置pom.xml文件
2.3.3 配置EditConfiguations的Maven啟動方式
命令:mybatis-generator:generate -e
2.4 解決@Repository標簽注解報錯問題
2.4.1 @Repository標簽改為@Mapper標簽
添加@Mapper注解之后,這個接口在編譯時會生成相應的實現類。但請注意,這個接口中不可以定義同名的方法,因為會生成相同的id,因此這個接口不支持重載。這樣做雖然能解決問題,但以后都要為每個Dao層的接口添加@Mapper注解
2.4.2 不修改@Repository注解,在啟動類中添加@MapperScan(“xxxx”)注解,用于掃描Mapper類的包。
掃描多個包:@MapperScan({”com.zking.dao”,”com.zking.pojo”})@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = Springboot03Application.class)3.配置PageHelper分頁插件
3.1 引入依賴
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.3</version></dependency>3.2 配置application.yml
#pagehelper分頁插件配置pagehelper:helperDialect: mysqlreasonable: truesupportMethodsArguments: trueparams: count=countSql3.3 創建分頁AOP
注:必須開啟動態代理@EnableAspectJAutoProxy4.配置log日志
Spring Boot在所有內部日志中使用Commons Logging,但是默認配置也提供了對常用日志的支持,如:Java Util Logging,Log4J, Log4J2和Logback。每種Logger都可以通過配置使用控制臺或者文件輸出日志內容。
4.1 配置application.yml
#顯示日志logging:level: com.zking.springboot01.mapper: debug5.其他
5.1 SpringBoot啟動項配置:
//自動掃描Mapper目錄@MapperScan("com.zking.項目名.mapper")//啟用事物管理器@EnableTransactionManagement 配置@transactional//啟用動態代理@EnableAspectJAutoProxy總結
以上是生活随笔為你收集整理的springboot与mybatis整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MATLAB 过时了吗?
- 下一篇: 计算机术语 日语,常用日语计算机词汇~~