• SpringBoot整合MyBatis


    1.在原有的依赖中,添加MyBatis的依赖

    <!--SpringBoot整合MyBatis-->
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
    </dependency>

    2.配置相关数据源信息(application.yml)。

    #DataBase Configuration
    spring:
    datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springbootdemo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    username: root
    password: 123
    #SpringDataJPA Configuration
    jpa:
    database: mysql
    show-sql: true
    generate-ddl: true

    3.创建实体类,对应数据库表中的字段,并添加getter、setter和toString方法

    4.创建mapper接口和对应的sql映射文件,二者在同一个包下。

    MyUserMapper

    package com.gxh.mapper;
    
    import com.gxh.entity.MyUser;
    
    import java.util.List;
    
    public interface MyUserMapper {
        List<MyUser> getUserList();
    }

    MyUserMapper .xml:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.gxh.mapper.MyUserMapper">
        <select id="getUserList" resultType="com.gxh.entity.MyUser">
            select * from user
        </select>
    </mapper>

    5.在SpringBoot启动类上添加@MapperScan注解

     6.运行,会报500错误,

    解决办法:

      方法1:将mapper.xml建在resources目录下,和mapper类在同一目录结构下。

      方法2:在pom.xml中添加下面代码

    <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.*</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>

    再次运行,会发现,可以出现数据了

  • 相关阅读:
    阿里云主机如何重装系统?
    Linux下mysql新建账号及权限设置
    Ahead-of-time compilation(AOT)
    XBOX ONE游戏开发常见问题
    云计算之路-阿里云上:RDS用户的烦恼
    数字证书原理
    《你不常用的c#之二》:略谈GCHandle
    批处理文件指定jre路径启动java桌面应用程序
    关于OAUTH2.0的极品好文
    第一天接触Orchard
  • 原文地址:https://www.cnblogs.com/gxh494/p/11799205.html
Copyright © 2020-2023  润新知