zoukankan      html  css  js  c++  java
  • SpringBoot整合mybatis的简单案例

    1.在springboot项目中的pom.xml中添加mybatis的依赖

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>

    2.在src/main/resources/application.yml中配置数据源信息

    # DB Configation
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
        username: root
        password: root
    
    # JAPConfigration
      jpa:
        database: mysql
        show-sql: true
        generate-ddl: true
    在连接数据库的过程中可能会出现SQLException,可能是时区问题导致的,加上url路径后面的“serverTimezone = GMT”即可
    3.在主启动类的同级创建po包和mapper包,在po包中创建实体类,编写pojo;在mapper包中创建mapper接口和mapper映射文件
    mapper.java
    
    
    package com.hxy.springbootdemo1.demo.mapper;
    
    import com.hxy.springbootdemo1.demo.pojo.MUser;
    
    import java.util.List;
    
    public interface UserMapper {
        List<MUser> getUserList();
    }
    mapper.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.hxy.springbootdemo1.demo.mapper.UserMapper">
        <select id="getUserList" resultType="com.hxy.springbootdemo1.demo.pojo.MUser">
            select * from user
        </select>
    </mapper>

    4.手动配置mybatis的包扫描

      在主启动类添加@MapperScan

      如果出现错误:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.offcn.mapper.UserMapper.getUserList

      有如下两种方法解决:

      1 把映射文件 放到resources 目录下 结构目录一模一样

      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>
     </build>
  • 相关阅读:
    Python
    deleted
    deleted
    ZOJ 3593 One Person Game(ExGcd + 最优解)题解
    ZOJ 3609 Modular Inverse(扩展欧几里得)题解
    P2234 [HNOI2002]营业额统计(Splay树)题解
    FJUT seventh的tired树上路径(01字典树)题解
    HDU 4825 Xor Sum(01字典树)题解
    Newcoder Metropolis(多源最短路 + Dijkstra堆优化)题解
    HDU 5938 Four Operations(乱搞)题解
  • 原文地址:https://www.cnblogs.com/hxy-programmer/p/11801948.html
Copyright © 2011-2022 走看看