SpringBoot之整合Mybatis

1.添加數據庫及相關數據庫表(此處數據庫爲mysql)
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.新建maven工程並在pom.xml中添加相關依賴jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.caixing.learn.springboot</groupId>
    <artifactId>springboot_mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_mybatis</name>
    <url>http://maven.apache.org</url>
    <!-- 添加SpringBoot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <properties>
        <!-- 通用配置 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!-- 數據庫相關配置版本 -->
        <druid.version>1.1.9</druid.version>
        <mybatis.version>1.3.1</mybatis.version>
        <!-- 數據庫鏈接加密工具類版本 -->
        <jasypt-spring-boot-starter.version>2.0.0</jasypt-spring-boot-starter.version>

        <!-- MyBatis-Generator版本 -->
        <mybatis-generator-core.version>1.3.5</mybatis-generator-core.version>
        <mybatis-generator-maven-plugin.version>1.3.5</mybatis-generator-maven-plugin.version>
        <mapper.version>3.4.3</mapper.version>
        <!-- Java接口和實體類 -->
        <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
        <targetMapperPackage>com.caixing.learn.springboot.mapper</targetMapperPackage>
        <targetModelPackage>com.caixing.learn.springboot.entity</targetModelPackage>
        <!-- XML生成路徑 -->
        <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
        <targetXMLPackage>mapper</targetXMLPackage>

    </properties>

    <dependencies>
        <!-- 添加WEB -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 添加熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!-- 添加mysql數據庫插件 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 添加druid連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- 添加mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- 數據庫加密工具類 -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>${jasypt-spring-boot-starter.version}</version>
        </dependency>
        <!-- 添加Mybatis-Generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>${mybatis-generator-core.version}</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <!--集成通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <!-- 建議使用最新版本 -->
            <version>${mapper.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
            <!--mybatis自動生成代碼插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>${mybatis-generator-maven-plugin.version}</version>
                <configuration>
                    <!-- 是否覆蓋 -->
                    <overwrite>true</overwrite>
                    <!--允許移動生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 自動生成的配置,${basedir}表示項目根目錄 ,configurationFile默認在resource目錄下 -->
                    <!--<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> -->
                </configuration>
                <dependencies>
                    <!--mysql驅動包 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                        <scope>runtime</scope>
                    </dependency>
                    <!--集成通用mapper依賴 -->
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>${mapper.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>
3.在src/main/resources下添加generatorConfig.xml【用於自動生成mapper、entity和xml】
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

   <!-- 引入配置文件 -->
   <properties resource="config/application-dev.properties" />

   <!-- context:生成一組對象的環境 id:必選,上下文id,用於在生成錯誤時提示 defaultModelType:指定生成對象的樣式 
      1conditional:類似hierarchical 2flat:所有內容(主鍵,blob)等全部生成在一個對象中; 3hierarchical:主鍵生成一個XXKey對象(key 
      class)Blob等單獨生成一個對象,其他簡單屬性在一個對象中(record class) targetRuntime: 1MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample 
      2MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample introspectedColumnImpl:類全限定名,用於擴展MBG -->
   <context id="Mysql" targetRuntime="MyBatis3">
      <!--https://mapperhelper.github.io/docs/3.usembg/,自動生成代碼的通用mapper插件 -->
      <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
         <property name="mappers" value="tk.mybatis.mapper.common.Mapper" />
         <!-- caseSensitive默認false,當數據庫表名區分大小寫時,可以將該屬性設置爲true -->
         <!-- <property name="caseSensitive" value="true"/> -->
      </plugin>
      <!-- 註釋 -->
      <commentGenerator>
         <!-- 是否取消自動生成的註釋 -->
         <!--<property name="suppressAllComments" value="true"/> -->
         <!-- 是否生成註釋代時間戳 -->
         <!--<property name="suppressDate" value="false" /> -->
      </commentGenerator>

      <jdbcConnection driverClass="com.mysql.jdbc.Driver"
         connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}">
         <!-- 針對mysql數據庫 -->
         <property name="useInformationSchema" value="true" />
      </jdbcConnection>

      <!-- 類型轉換 -->
      <javaTypeResolver>
         <!-- 是否使用bigDecimal false可自動轉化以下類型(Long, Integer, Short, etc.-->
         <property name="forceBigDecimals" value="true" />
      </javaTypeResolver>

      <!-- 生成實體類地址 -->
      <javaModelGenerator targetPackage="${targetModelPackage}"
         targetProject="${targetJavaProject}">
         <!-- 是否在當前路徑下新加一層schema,egfase路徑com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] -->
         <!--<property name="enableSubPackages" value="true" /> -->
         <!-- 是否針對string類型的字段在set的時候進行trim調用 -->
         <!--<property name="trimStrings" value="true" /> -->
      </javaModelGenerator>

      <!-- 生成mapxml文件 -->
      <sqlMapGenerator targetPackage="${targetXMLPackage}"
         targetProject="${targetResourcesProject}">
         <!-- 是否在當前路徑下新加一層schema,egfase路徑com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] -->
         <!-- <property name="enableSubPackages" value="true" /> -->
      </sqlMapGenerator>

      <!-- 生成mapxml對應client,也就是接口dao -->
      <javaClientGenerator type="XMLMAPPER"
         targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}">
         <!-- 是否在當前路徑下新加一層schema,egfase路徑com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] -->
         <!--<property name="enableSubPackages" value="true" /> -->
      </javaClientGenerator>


      <table tableName="%" enableCountByExample="false"
         enableUpdateByExample="false" enableDeleteByExample="false"
         enableSelectByExample="false" selectByExampleQueryId="false">
         <columnOverride column="is_display" javaType="Boolean" />
         <columnOverride column="content_type" javaType="Integer" />
         <columnOverride column="is_deleted" javaType="Boolean" />
         <columnOverride column="is_reproduced" javaType="Boolean" />
         <columnOverride column="is_finished" javaType="Boolean" />
      </table>

   </context>
</generatorConfiguration>

4.src/main/resources下添加application.properties文件【用於添加數據庫相關配置信息】
#=========================全局配置=============================
#端口
server.port=9090

#=====================mysql的相關配置============================
spring.datasource.url = jdbc:mysql://192.168.2.106:3306/test1?characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver

#=====================鏈接池的相關配置=============================
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.maxActive=20
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.validationQuery=select 1
spring.datasource.poolPreparedStatements=1
spring.datasource.maxOpenPreparedStatements=20

#=====================mybatis的相關配置============================
mybatis.type-aliases-package=com.caixing.learn.springboot.entity
mybatis.mapperLocations=classpath:mapper/*.xml

5.編寫mybatis的配置類,dao層,service層
MybatisMapperScanConfig.java
package com.caixing.learn.springboot.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * 
 * <Description> mybatis的掃描配置文件 <br> 
 * @author caixing<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2018327<br>
 */
@Configuration
@AutoConfigureAfter(MybatisConfig.class)
public class MabatisMapperScanConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.caixing.learn.springboot.mapper");
        return mapperScannerConfigurer;
    }
}

MybatisConfig.java

package com.caixing.learn.springboot.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.jasypt.util.text.BasicTextEncryptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 
 * <Description> 添加mybatismapper配置信息 <br> 
 * @author caixing<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2018327<br>
 */
@ConfigurationProperties
public class MybatisConfig {

    /**
     * 注入環境變量的值
     */
    @Autowired
    private Environment environment;

    private BasicTextEncryptor stringEncryptor = new BasicTextEncryptor();

    @Bean("druidDataSource")
    public DataSource duridDataSource() {

        // 獲取加密參數
        stringEncryptor.setPassword(environment.getProperty("jasypt.encryptor.password"));

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
        String encoderUserName = environment.getProperty("spring.datasource.username");
        druidDataSource.setUsername(stringEncryptor.decrypt(encoderUserName));
        String encoderPass = environment.getProperty("spring.datasource.password");
        druidDataSource.setPassword(stringEncryptor.decrypt(encoderPass));
        druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.driverClassName"));
        druidDataSource.setMaxActive(Integer.parseInt(environment.getProperty("spring.datasource.maxActive")));
        druidDataSource.setInitialSize(Integer.parseInt(environment.getProperty("spring.datasource.initialSize")));
        druidDataSource.setMaxWait(Long.parseLong(environment.getProperty("spring.datasource.maxWait")));
        druidDataSource.setMinIdle(Integer.parseInt(environment.getProperty("spring.datasource.minIdle")));
        druidDataSource.setValidationQuery(environment.getProperty("spring.datasource.validationQuery"));
        druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(environment.getProperty("spring.datasource.poolPreparedStatements")));
        druidDataSource.setMaxOpenPreparedStatements(Integer.parseInt(environment.getProperty("spring.datasource.maxOpenPreparedStatements")));
        return druidDataSource;
    }

    /**
     * 獲取SqlSessionFactory
     *
     * @param druidDataSource
     * @return
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(DataSource druidDataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(druidDataSource);
        bean.setTypeAliasesPackage(environment.getProperty("mybatis.type-aliases-package"));
        //添加XML目錄
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String xmlPath = environment.getProperty("mybatis.mapperLocations");
        try {
            bean.setMapperLocations(resolver.getResources(xmlPath));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 增加事務
     *
     * @param druidDataSource
     * @return
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DataSource druidDataSource) {
        return new DataSourceTransactionManager(druidDataSource);
    }

}

啓動mybatis插件,自動生成entity、mapper、mapper.xml(命令爲:mybatis-generator:generate)
6.測試配置是否成功
UserService.java
package com.caixing.learn.springboot.service;

import com.caixing.learn.springboot.entity.User;

public interface UserService {

    public int createUser(User user);

}

UserServiceImpl.java

package com.caixing.learn.springboot.service.impl;

import com.caixing.learn.springboot.entity.User;
import com.caixing.learn.springboot.mapper.UserMapper;
import com.caixing.learn.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public int createUser(User user) {
        int num =mapper.insert(user);
        return num;
    }
}

HelloController.java

package com.caixing.learn.springboot.controller;

import com.caixing.learn.springboot.entity.User;
import com.caixing.learn.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class HelloController {


    @Autowired
    private UserService service;

    @GetMapping("/create")
    @ResponseBody
    public String createUser() {
        String msg = "添加成功";
        User user = new User();
        user.setName("caixing");
        try {
            int num = service.createUser(user);
            if (num < 1) {
                msg = "添加失敗";
            }
        } catch (Exception e) {
            msg = "添加失敗";
        }
        return msg;
    }
}

App.java

package com.caixing.learn.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

啓動,並在瀏覽器訪問:http://127.0.0.1:9090/user/create

7.本示例的GitHub地址
https://github.com/caixingjava/springboot_mybatis
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章