其他分享
首页 > 其他分享> > Mybatis在springboot项目中的简单使用

Mybatis在springboot项目中的简单使用

作者:互联网

一、介绍

MyBatis 是一款优秀的持久层框架,它支持定制化SQL存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。


二、springboot中集成Mybatis所需的特有的相关依赖

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
    </dependency>
    <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
     </dependency>
     <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
     </dependency>

三、相关配置文件

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml #配置xml映射文件的目录
  config-location: classpath:mybatis/mybatis-config.xml #mybatis配置文件

spring:
  datasource:
    username: root
    password:
    url: jdbc:mysql://localhost:3306/sy_java_db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8 #jdbc数据库连接固定写法
    driver-class-name: com.mysql.cj.jdbc.Driver #对应使用的驱动
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="mysql">
        <!--配置Mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"/>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--配置连接数据库的四个基本信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/sy_java_db" />
                <property name="username" value="root" />
                <property name="password" value="" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
<!--被扫描的配置xml-->
        <mapper resource="mapper/UserDao.xml" />
    </mappers>
</configuration>
<?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.song.dao.UserDao"> <!--接口,定义操作数据的方法-->

    <resultMap type="com.song.entity.User" id="UserMap">  <!--实体类,类中属性对应所需查询的表的字段,这里包名使用entity,也可以是pojo-->
        <result property="userId" column="user_id" jdbcType="INTEGER"/> <!--实体类与表字段的映射关系,字段的数据类型-->
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
    </resultMap>

    <!--query single-->
    <select id="queryById" resultMap="UserMap">
        select
          user_id, `name`, age
        from sy_java_db.user
        where user_id = #{userId}
    </select>

    <!--query by id-->
    <select id="queryAll" resultMap="UserMap">
        select
          user_id, `name`, age
        from sy_java_db.user
    </select>

</mapper>

四、Java相关代码

package com.song.dao;

import com.song.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper //用以申明接口是Mapper接口,会自动被扫描
public interface UserDao {
    User queryById(int userId);

    List<User> queryAll();
}
package com.song.entity;


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

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -81805678943456282L;

    private int userId;

    private String name;

    private int age;
}

测试

  1. 创建Get请求传输userId获取用户名
package com.song.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.song.constant.MsgCode;
import com.song.dao.UserDao;
import com.song.entity.User;
import com.song.response.BaseResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
public class HomeController {
    @Resource
    private UserDao userDao;

    @Resource
    ObjectMapper objectMapper;

    @GetMapping("/getUserInfo")
    public Object home(HttpServletRequest request){
        int userId = Integer.parseInt(request.getParameter("userId"));
        User users = userDao.queryById(userId);
        String s;
        try {
            s = objectMapper.writeValueAsString(users);
        } catch (JsonProcessingException e) {
            return BaseResponse.fail(MsgCode.REQUEST_FAIL_OTHER_ERR.getCode(),MsgCode.REQUEST_FAIL_OTHER_ERR.getMessage());
        }
        return BaseResponse.ok(s);
    }
}

  1. 启动SpringBoot

  2. 使用postman进行测试

标签:java,springboot,song,userId,mybatis,简单,Mybatis,import,com
来源: https://www.cnblogs.com/sy19931020/p/16592498.html