1. 程式人生 > >SpringBoot的MyBatis框架搭建

SpringBoot的MyBatis框架搭建

一 增加相關依賴

<dependencies>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- 資料庫 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- 連線池 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>        
</dependencies>

二 application.properties

server.port=8080
#加入/demo字首
server.context-path=/demo

#DataSource
#資料庫驅動
jdbc.driver=com.mysql.jdbc.Driver
#資料庫連結
jdbc.url=jdbc:mysql://localhost:3306/o2o?useUnicode=true&characterEncoding=utf8&useSSL=false
#資料庫使用者名稱
jdbc.username=root
#資料庫密碼
jdbc.password=123456

#Mybatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
type_alias_package=com.imooc.demo.entity

三 mybatis配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置全域性屬性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys獲取資料庫自增主鍵值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 使用列標籤替換列別名 預設:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 開啟駝峰命名轉換:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

四 資料庫指令碼

1 建立資料庫

create database demo;

2 建立表

CREATE TABLE tb_area (
    area_id int(2) NOT NULL auto_increment,
    area_name varchar(200) NOT NULL,
    priority int(2) NOT NULL DEFAULT'0',
    create_time datetime DEFAULT NULL,
    last_edit_time datetime DEFAULT NULL,
    PRIMARY KEY(area_id),
    UNIQUE KEY UK_AREA(area_name)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;