美文网首页
SpringBoot 整合Mybatis框架

SpringBoot 整合Mybatis框架

作者: 木羽 | 来源:发表于2020-11-14 10:45 被阅读0次

第一步 导入Mybatis依赖 jdbc依赖以及 MySQL驱动

<!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
<!--jdbc-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

第二步 配置yml文件

spring:
  datasource:
    username: root
    password: 123456
    #serverTimezone 时区
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

#整合mybatis
mybatis:
  #别名设置
  type-aliases-package: com.muyu.pojo
  #设置xml文件mapper的位置  classpath:代表的是resources
  mapper-locations: classpath:mybatis/mapper/*.xml

此时已经可以通过mybatis连通数据库

加注解

Mapper中加@Mapper

@Mapper
public interface UserMapper {
    List<User> queryUserList();

service类中要加@Service

@Service
public class BookServiceImpl implements BookService {
附mybatis 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.muyu.mapper.UserMapper">
  
</mapper>

此处注意当参数类型为对象的时候,在进行调用的时候需要写成#{book.bname}
写成#{bname}的话会报错

<insert id="addBook" parameterType="Book">
        insert into bms_book(bname,author,type,inventory) VALUES(#{book.bname},#{book.author},#{book.type},#{book.inventory})
    </insert>

相关文章

网友评论

      本文标题:SpringBoot 整合Mybatis框架

      本文链接:https://www.haomeiwen.com/subject/uziibktx.html