SpringBoot五步配置Mybatis超簡教程

第一步:Maven裏面添加mybatis的引用jar包:

<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
</dependency>

第二步:在application.properties文件裏面添加如下代碼

#配置mysql數據源
spring.datasource.url=jdbc:mysql://your-mysql-url/database-name?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver

#security.basic.enabled=false

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl


## Mybatis 配置
mybatis.type-aliases-package=com.xfind.core.entity.xianyu
mybatis.mapper-locations=classpath:mapper/*.xml
#使全局的映射器啓用或禁用緩存。
mybatis.configuration.cache-enabled=true
#全局啓用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載。
mybatis.configuration.lazy-loading-enabled=true
#當啓用時,有延遲加載屬性的對象在被調用時將會完全加載任意屬性。否則,每種屬性將會按需要加載。
mybatis.configuration.aggressive-lazy-loading=true
#是否允許單條sql 返回多個數據集  (取決於驅動的兼容性) default:true
mybatis.configuration.multiple-result-sets-enabled=true
#是否可以使用列的別名 (取決於驅動的兼容性) default:true
mybatis.configuration.use-column-label=true
#允許JDBC 生成主鍵。需要驅動器支持。如果設爲了true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然可以執行。  default:false
mybatis.configuration.use-generated-keys=true
#指定 MyBatis 如何自動映射 數據基表的列 NONE:不隱射\u3000PARTIAL:部分  FULL:全部
mybatis.configuration.auto-mapping-behavior=partial
#這是默認的執行類型  (SIMPLE: 簡單; REUSE: 執行器可能重複使用prepared statements語句;BATCH: 執行器可以重複執行語句和批量更新)
mybatis.configuration.default-executor-type=simple
#使用駝峯命名法轉換字段。
mybatis.configuration.map-underscore-to-camel-case=true
#設置本地緩存範圍 session:就會有數據的共享  statement:語句範圍 (這樣就不會有數據的共享 ) defalut:session
mybatis.configuration.local-cache-scope=session
#設置但JDBC類型爲空時,某些驅動程序 要指定值,default:OTHER,插入空值時不需要指定類型
mybatis.configuration.jdbc-type-for-null=null
#如果數據爲空的字段,則該字段省略不顯示,可以通過添加配置文件,規定查詢數據爲空是則返回null。
mybatis.configuration.call-setters-on-nulls=true

第三步:設置啓動類:

//開啓定時任務
//@EnableScheduling
@SpringBootApplication
@EnableTransactionManagement//開啓事務管理
@MapperScan("com.xfind.core.mybatis")//與dao層的@Mapper二選一寫上即可(主要作用是掃包)
public class StartUp {
    public static void main(String[] args) {
        SpringApplication.run(StartUp.class, args);
    }
}

第四步:添加mapper文件和編寫dao代碼以及service和controller代碼,
1、我是在core的modules裏面的resources文件夾下新建mapper文件夾,下面保存所有數據庫訪問的sql。
2、新建實體類,我是在entity文件夾下創建的
2、在dao層下新建mapper裏面的方法
3、在service層新建調用dao層類的邏輯代碼
4、在controller層新建調用service層的邏輯代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章