SpringBoot整合mybatis

导入依赖

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

yaml配置文件

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

#整合mybatis
mybatis.type-aliases-package=com.ji.pojo
#注册mapper文件
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

User实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

Mapper接口

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper  //这个注解表示这是一个mybatis mapper类 类似mybatis namespace中命名空间mapper类
@Repository
public interface UserMapper {
   // int age=18;        //public static final 接口中方法变量默认访问权限
    List<User> queryUserList();  //public abstract
    User queryUserById();
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
}

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.ji.mapper.UserMapper">
    <!--<cache/>  开启缓存-->
    <select id="queryUserList" resultType="User">
        select * from `user`
    </select>
    <select id="queryUserById" resultType="User" parameterType="int">
        select * from user where `id`=#{id}
    </select>
    <!--对象中的属性可以直接取出来-->
    <insert id="addUser" parameterType="User">
        insert into `user`(`id`,`name`,`pwd`)
        values(#{id},#{name},#{pwd});
    </insert>
    <!--当传入参数为user其中有三个参数,如果sql语句只需要两个数据,那么在传入user实体时有一个参数就会为null值,这时使用map较好-->
    <update id="updateUser" parameterType="User">
        update `user` set `name` =#{name}  <!--"%"#{name}"%"   ->sql注入问题-->
        where `id`=#{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from `user` where `id`=#{id}
    </delete>
</mapper>

测试类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/hello")
    public List<User> queryUser(){
        List<User> users = userMapper.queryUserList ();
        for (User user : users) {
            System.out.println (user);
        }
        return users;
    }
}

使用mybatis整合springBoot后,无需配置事务,springBoot自动配置

上一篇:课程管理之课程信息确认的后端接口


下一篇:ResourceDictionary