1. 程式人生 > >SpringBoot學習記錄(三)——整合Mybatis

SpringBoot學習記錄(三)——整合Mybatis

以前整合了Spring+SpringMVC+Mybatis,今天用SpringBoot整合了Mybatis,發現這個比之前的SSM的整合方便的太多,省去大量的配置檔案,也許是我還沒用到很深入吧,話不多說,直接進入正題。

1、建立一個SpringBoot專案:

2、下一步:

 3、然後加入一些需要的依賴,這裡用的SpringBoot2:

4、建立成功之後檢視一下pom裡面的配置:

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.thr</groupId>
    <artifactId>spring-boot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- mybatis generator 自動生成程式碼外掛 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

注意:pom檔案裡面的 mybatis generator 自動生成程式碼外掛 是自己要加進去的:

<!-- mybatis generator 自動生成程式碼外掛 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>

5、配置application.properties檔案,一般不使用這個,推薦使用application.yml,將properties改成yml就可以了,但是這裡方便就不該了。

server.port=8080

#mapper檔案的位置
mybatis.mapper-locations=classpath:mapper/*.xml
#對應實體類的位置
type-aliases-package=com.thr.entity  

#配置資料來源
spring.datasource.username=root
spring.datasource.password=root
#使用druid資料來源
#type: com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_user?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8

6、然後建立資料庫db_user:

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) DEFAULT NULL,
  `password` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'admin', '123');

7、使用Mybatis的Generator自動生成類,在專案的resources下新增generatorConfig.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>

    <!-- 資料庫驅動:選擇你的本地硬碟上面的資料庫驅動包-->
    <classPathEntry  location="E:\mysql-connector-java-5.1.28-bin.jar"/>

	<context id="testTables" targetRuntime="MyBatis3">

		<commentGenerator>
			<!-- 是否去除自動生成的註釋 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>

		<!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			            connectionURL="jdbc:mysql://localhost:3306/db_user"
                        userId="root"
                        password="root">
		</jdbcConnection>
		<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
			connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:user"
			userId="yycg"
			password="yycg">
		</jdbcConnection> -->

		<!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL 和 
			NUMERIC 型別解析為java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- targetProject:生成PO類的位置 -->
		<javaModelGenerator targetPackage="com.thr.entity"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
			<!-- 從資料庫返回的值被清理前後的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
        <!-- targetProject:mapper對映檔案生成的位置 -->
		<sqlMapGenerator targetPackage="mapper"
			targetProject=".\src\main\resources">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- targetPackage:mapper介面生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.thr.dao" 
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>

		<!-- 指定資料庫表 tableName是資料庫中的表名或檢視名 domainObjectName是實體類名-->
        <table tableName="t_user"
               domainObjectName="User"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">

        </table>
		
		<!-- 有些表的欄位需要指定java型別
		 <table schema="" tableName="">
			<columnOverride column="" javaType="" />
		</table> -->
	</context>
</generatorConfiguration>

8、然後在IDEA的右邊找到Maven Projects,找到之前的外掛,雙擊:注意!!!同一張表一定不要執行多次,因為mapper的對映檔案中會生成多次的程式碼,切記不要多次執行!!!

 執行完成後就可以看到:

 9、開啟類SpringbootMybatisDemoApplication.java,這個是springboot的啟動類。我們需要新增點東西:

注意:@MapperScan("com.thr.dao")這個註解非常的關鍵,這個對應了專案中mapper(dao)所對應的包路徑,很多同學就是這裡忘了加導致異常的。如果不在啟動類這裡加,也可以在Mapper類上面添加註解@Mapper,建議使用上面那種,不然每個mapper加個註解也挺麻煩的。

package com.thr;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.thr.dao")
public class SpringBootMybatisApplication {

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

}

10、然後就是Controller,Service層了:

UserController類:

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/user")
    public Object User(){
        return userService.findAllUser();
    }
}

UserMapper下要加一個方法List<User> findAllUser():

public interface UserMapper {

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> findAllUser();
}

 所以相應的Mapper.xml也要新增一條SQL語句;

    <select id="findAllUser" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from t_user
    </select>

UserService介面:

/**
 * @author
 * @name
 */
public interface UserService {

    List<User> findAllUser();
}

UserServiceImpl實現類:

/**
 * @author
 * @name
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }
}

總體目錄結構如下:

 11、執行啟動類,然後訪問http://localhost:8080/user

成功訪問,SpringBoot成功整合Mybatis。

如果訪問不了,那就在pom下面的build中新增下面的程式碼:這是IDEA的原因,有時候有些檔案沒有編譯到target下,配置下面這個後就可以了。

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>