SpringBoot整合Mybatis(yml方式)

  本来打算写个使用Sharding-JDBC的例程,但是在搭建Mybatis的过程中,一波三折,因为好久没搭建项目了,另外加上换了电脑。所以很破折,在这里记录一下Spring Boot整合Mybatis吧。可能很简单,但是我长时间没用忘记了,我这里备忘一下吧。

一、项目目录结构

  注意这里Application文件的位置,它是与controller、entity、mapper、service等包处于并列的关系。

  

二、数据库文件

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user_00
-- ----------------------------
DROP TABLE IF EXISTS `t_user_00`;
CREATE TABLE `t_user_00`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `user_id` int(0) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `age` int(0) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

三、pom.xml

<?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 https://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.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gougou</groupId>
    <artifactId>shardingjdbc-shardingtable-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shardingjdbc-shardingtable-demo</name>
    <description>shardingjdbc-shardingtable-demo</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
    </dependencies>

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

</project>

四、application.yml

# 数据源
spring:
  application:
    name: shardingjdbc-shardingtable-demo
  datasource:
    url: jdbc:mysql://localhost:3306/sharding_0?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    dbcp2:
      min-idle: 5                                # 数据库连接池的最小维持连接数
      initial-size: 5                            # 初始化连接数
      max-total: 5                               # 最大连接数
      max-wait-millis: 150                       # 等待连接获取的最大超时时间

# mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml    # mapper映射文件位置
  type-aliases-package: com.gouggou.shardingtable.entity    # 实体类所在的位置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #用于控制台打印sql语句

五、启动类Application

  说明:

  1、@MapperScan的:扫描mapper接口的位置

  2、@ComponentScan:如果Application文件的位置不是与controller、entity、mapper、service等包处于并列的关系。就要用此注解,否则可以不用;

@MapperScan("com.gouggou.shardingtable.mapper")
@SpringBootApplication
public class Application {

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

}

六、controller

@RequestMapping("student")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("save")
    public String save() {
        User user = new User();
        user.setUserId(new Random().nextInt( 1000 ) + 1);
        user.setName("张三"+user.getUserId());
        user.setAge(new Random().nextInt( 80 ) + 1);
        userService.insert(user);
        return user.getName()+"创建成功!";
    }

}

七、service

public interface UserService {

    Integer insert(User u);

    List<User> findAll();

    List<User> findByUserIds(List<Integer> userIds);

}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer insert(User u) {
        return userMapper.insert(u);
    }

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

    @Override
    public List<User> findByUserIds(List<Integer> userIds) {
        return userMapper.findByUserIds(userIds);
    }
}

八、entity

@Data
public class User implements Serializable {

    private static final long serialVersionUID = -5514139686858156155L;

    private Integer id;

    private Integer userId;

    private String name;

    private Integer age;

}

九、Mapper

@Repository
public interface UserMapper {

    Integer insert(User u);

    List<User> findAll();

    List<User> findByUserIds(List<Integer> userIds);

}
<?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.gouggou.shardingtable.mapper.UserMapper" >
    <resultMap id="resultMap" type="com.gouggou.shardingtable.entity.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_id" property="userId" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>

    <insert id="insert">
    insert into t_user_00 (user_id,name,age) values (#{userId},#{name},#{age})
  </insert>

    <select id="findAll" resultMap="resultMap">
        select <include refid="columnsName"/> from t_user_00
    </select>

    <select id="findByUserIds" resultMap="resultMap">
        select <include refid="columnsName"/> from t_user_00 where user_id in (
        <foreach collection="list" item="item" separator=",">
            #{item}
        </foreach>
        )

    </select>

    <sql id="columnsName">
     id,user_id,name,age
  </sql>
</mapper>

十、遇到的问题

  1、idea 右键无java class选项

    2、maven仓库中产生后缀是LastUpdated的文件

原文地址:https://www.cnblogs.com/DDgougou/p/12636649.html

时间: 2024-08-01 04:58:56

SpringBoot整合Mybatis(yml方式)的相关文章

SpringBoot整合Mybatis之Annotation

首先需要下载前面一篇文章的代码,在前一章代码上进行修改. SpringBoot整合Mybatis(注解方式) 复制前一个项目,修改配置文件,mybatis的相关配置为: mybatis: type-aliases-package: con.mybatis.springboot_mybatis.model configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdO

SpringBoot整合Mybatis传参的几种方式

转自https://blog.csdn.net/irelia_/article/details/82347564 在SpringBoot整合Mybatis中,传递多个参数的方式和Spring整合Mybatis略微有点不同,下面主要总结三种常用的方式 一.顺序传参法 Mapper层: 传入需要的参数 public interface GoodsMapper { public Goods selectBy(String name,int num); }1234Mapper.xml: *使用这种方式,

SpringBoot整合MYBATIS,多数据源,事务,支持JAVA -JAR 启动.

用了一段时间SpringBoot,之前配置MYBATIS ,在打包WAR 放到tomcat下正常,但是WAR已经过时了,现在流行直接打包JAR 丢到DOCKER 里,无奈JAR 启动的时候MAPPER 扫描有问题,只能说之前整合MYBATIS 的方式不对. 这次的整合应该是不存在加载顺序引起的问题,使用了一段时间,妥妥的,记录下来 pom.xml <parent> <groupId>org.springframework.boot</groupId> <artif

SpringBoot整合Mybatis多数据源 (AOP+注解)

SpringBoot整合Mybatis多数据源 (AOP+注解) 1.pom.xml文件(开发用的JDK 10) <?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:s

SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统

1.前言本文主要介绍使用SpringBoot与shiro实现基于数据库的细粒度动态权限管理系统实例. 使用技术:SpringBoot.mybatis.shiro.thymeleaf.pagehelper.Mapper插件.druid.dataTables.ztree.jQuery 开发工具:intellij idea 数据库:mysql.redis 2.表结构还是是用标准的5张表来展现权限.如下图:image 分别为用户表,角色表,资源表,用户角色表,角色资源表.在这个demo中使用了mybat

SpringBoot整合Mybatis【非注解版】

接上文:SpringBoot整合Mybatis[注解版] 一.项目创建 新建一个工程 ? 选择Spring Initializr,配置JDK版本 ? 输入项目名 ? 选择构建web项目所需的staters(启动器) ? 选择与数据库相关的组件 ? 分析:Spring Boot基本上将我们实际项目开发中所遇到的所有场景都做了封装.它将所有的功能场景都抽取出来,做成了一个个的staters(启动器),只需要在项目的pom.xml配置文件里面引入这些starter相关场景的所有依赖都会导入进来.需要什

SpringBoot 整合MyBatis案例详解

SpringBoot约定大于配置的特点,让框架的配置非常简洁,与传统的SSM框架相比,简化了大量的XML配置,使得程序员可以从繁琐的配置中脱离出来,将精力集中在业务代码层面,提高了开发效率,并且后期的维护成本也大大降低. 从源码中可以看到,每一个springboot集成的jar包也是一个maven的子module,springboot已经将相关依赖的jar包自动添加到工程中,不需要开发人员手动去添加了,这也是springboot能够简化配置的一个重要原因. 下面开始说明springboot是如何

springboot整合mybatis通用Mapper

参考: https://blog.csdn.net/x18707731829/article/details/82814095 https://www.jianshu.com/p/6d2103451dcb SpringBoot整合MyBatis Generator可以帮助我们快速生成实体类.接口.mapper.xml文件,可以提高开发的效率,但是每次新增表都要执行一次Generator生成相应的代码,这样重复的操作生成增删查改重复的的代码,有没有一种通用的接口,不用生成mapper.xml文件,

练习小记2:SpringBoot整合MyBatis

本文主要介绍SpringBoot整合MyBatis的初步过程以及需要注意的细节. SpringBoot简介 官网https://spring.io/projects/spring-boot/ ? MyBatis简介 官网:https://mybatis.org/mybatis-3/zh/index.html MyBatis的优势: 历史发展 MyBatis是由Ibatis发展而来的,Ibatis1.x和Ibatis2.x,都称为Ibatis,在Ibatis3.x版本及以后都称为:MyBatis

SpringBoot整合mybatis使用pageHelper插件进行分页操作

SpringBoot整合mybatis分页操作 SpringBoot整合Mybatis进行分页操作,这里需要使用Mybatis的分页插件:pageHelper, 关于pageHelper的介绍,请查看官方文档: https://pagehelper.github.io/ 1.使用前配置 关于pageHelper的使用配置,主要有以下2个步骤: 1.1.在pom文件中导入pageHelper依赖 <dependency> <groupId>com.github.pagehelper&