【springBoot】Springboot整合mybatis

本文介绍如何使用SpringBoot整合MyBatis,并通过注解和配置文件两种方式实现数据库操作。包括搭建环境、测试数据库连接、定义实体类、创建Mapper接口及XML映射文件等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

本博客用springboot通过注解版和配置文件版两种方式整合mybatis

1、pom坐标
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
2、yml文件
server:
  port: 8083
spring:
  datasource:
    username: root
    password: XXXXXXXXX
    url: jdbc:mysql://152.136.203.163:3306/jdbc?useUnicode=true&characterEncoding=UTF-8  #防止插入的数据乱码
mybatis:
  configuration:
    map-underscore-to-camel-case: true # 数据库中的下划线转驼峰配置

3、用springbootTest进行测试是否数据库连接成功
@RunWith(SpringRunner.class)
@SpringBootTest
public class Testd {
    @Autowired
    DataSource dataSource;
    @Test
    public void testDatasource() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

在这里插入图片描述
如下图默认数据源用的是hikari.HikariDataSource作为数据源头。这样就代表数据库连接成功了

4、准备两个实体Department 、Employee

在这里插入图片描述

5、用注解的方式访问数据库

5.1 mapper

@mapper用来指定这是操作数据库的mapper

// 指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptByid(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")  // 主键自增长(插入数据后要根据数据的id进行其他的操作问题)
    @Insert("insert into department(department_name) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set department_name=#{departmentName} where id = #{id}")
    public int updateDept(Department department);
}

注意以上都是设计到一个参数,如果是两个参数,那么必须要用@param注解
eg

@Select("select * from user where id=#{id}" && pwd=#{pwd})
    User getUserById(@Param("id") int id,@Param("pwd") int pwd);

基本类型的参数或者String类型,需要加上
引用类型不需要加
如果只有一个基本类型的话,可以忽略,但是建议都加上!
我们在SQL中引用的就是我们这里的@Param("")中设定的属性名

5.2 controller(resultFul风格接口)
@RestController
public class DeptController {
    @Autowired
    private DepartmentMapper departmentMapper;

    @PostMapping ("/dept")
    public Department insertDepartment(@RequestBody Department department){
         this.departmentMapper.insertDept(department);
         return department;
    }

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
       return this.departmentMapper.getDeptById(id);
    }
    @PutMapping("/dept")
    public int updateDepartment(@RequestBody Department department){
       return this.departmentMapper.updateDept(department);
    }
    
    @DeleteMapping("/dept/{id}")
    public int deleteDepartment(@PathVariable("id") Integer id){
        return this.departmentMapper.deleteDeptByid(id);
    }
}
5.3 用postman测试接口

就测试一个,插入的,如下图,先改成post请求,输入一个参数,然后返回一个带id的数据,这个带id是主键自增长实现的
在这里插入图片描述

6、用配置文件的方式
6.1mapper

首先我们为了不用每一个接口都写上@Mapper注解,我们可以在启动类上加上@MapperScan来讲接口扫描到容器中。

@MapperScan("com.atguigu.testdata.mapper")  // 将mapper接口扫描到容器中

mapper

//@Mapper或者@MapperScan将接口扫描到容器中
public interface EmployeeMapper {
    public  Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}
6.2 配置文件

(1)首先Mybatis 托管到了gitHub上,所以我们进入到gitHub上,然后搜索Mybatis在这里插入图片描述
(2)点击mybatis3 ,进入到新的页面,然后找到文档
在这里插入图片描述

(3)进入到mybatis 的官方文档,我们点击Getting Started 然后找到Exploring Mapped SQL Statements,复制下面内容到我们的.xml文件中
在这里插入图片描述
在这里插入图片描述
(4)EmployeeMapper.xml:
在这里插入图片描述

(5)写我们的sql

<?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.atguigu.testdata.mapper.EmployeeMapper">  <!--namespace是mapper下的接口-->
    <select id="getEmpById" resultType="com.atguigu.testdata.entity.Employee">
        select * from employee where id=#{id}
    </select>

    <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
        insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

(6) 在配置文件中设置.xml生效

 #如下让mybatis知道xml文件的存在,mapper-locations是一个数组,我们可以配置多个
  mapper-locations: mybatis/mapper/*.xml

(7) Controller

@RestController
public class EmpController {

    @Autowired
    private EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        return this.employeeMapper.getEmpById(id);
    }

    @PostMapping("/emp")
    public Employee InsertEmp(@RequestBody Employee employee){
         this.employeeMapper.insertEmp(employee);
         return employee;
    }
}

总结

在写demo的过程中遇到了一个特别难搞的问题,就是怎么都不能将EmployeeMapper.xml让mybatis识别,最后我们可以尝试clean install 就可以成功解决问题

<think>好的,我现在需要分析用户提供的这段JavaScript代码,并解释它的功能。首先,我会通读代码,理解每个部分的作用。 这段代码定义了一个名为getQ的函数。函数一开始获取了user_nickname输入框的值,存储在userid变量中。如果userid是null或undefined,函数返回false。否则,发起一个AJAX POST请求到../services/Qxgl.ashx,传递action和id参数。请求头里有一个Authorization令牌,看起来像是某种认证信息。 成功回调函数处理返回的msg数据,遍历msg.ds数组,对每个item,通过typeid设置对应的复选框为选中状态。然后收集所有选中的复选框的值,用逗号拼接后去掉最后一个逗号,将结果填入typename输入框。 接下来,我需要确认各个部分的细节是否正确。例如,检查jQuery选择器是否正确,AJAX调用的参数是否合理,以及数据处理是否有潜在错误。比如,$.each遍历msg.ds是否正确,假设msg.ds是一个数组。另外,拼接结果时使用substring去除末尾逗号是否可靠,是否有更稳妥的方法。 还要注意可能的安全问题,比如硬编码的Authorization头,这可能存在安全风险,但用户可能已经处理了。此外,用户权限验证是否在服务端进行,这里只是前端控制,需提醒用户不能仅依赖前端验证。 最后,将这些分析整理成结构清晰的解释,分步骤说明代码的功能和潜在注意事项,确保用户能够理解每个部分的作用及可能的改进点。</think>这是一个典型的基于jQuery的AJAX请求实现,主要用于获取并设置用户权限信息。让我们分步骤解析这个函数的功能: 1. **函数定义与用户ID获取** ```javascript var getQ = function () { var userid = $('#user_nickname').val(); // 获取用户输入框的值 ``` 2. **空值校验** ```javascript if (userid == null || userid == undefined) { // 验证用户ID有效性 return false; } ``` 3. **AJAX请求配置** ```javascript $.ajax({ type: "POST", // 使用POST方法 url: "../services/Qxgl.ashx", // 后端接口地址 headers: { // 请求头认证信息 "Authorization": "0772A4AA051DDEBB393DC164B19A32E57C4FEEAB27A77820" }, ``` 4. **请求参数传递** ```javascript data: { action: "getQ", // 执行动作类型 id: userid // 传递用户ID参数 }, ``` 5. **成功回调处理** ```javascript success: function (msg) { // 遍历返回数据集 $.each(msg.ds, function (index, item) { // 根据typeid勾选对应复选框 $('#a' + item.typeid).attr("checked", true); }) // 拼接选中值 var result = ""; $("input[name='select_checkbox']:checked").each(function () { result += $(this).val() + ','; }); // 去除末尾逗号 if (result != "") { result = result.substring(0, result.lastIndexOf(',')); } // 填充到显示框 $("#typename").val(result); } ``` **功能总结**: - 这是一个用户权限查询功能 - 通过用户输入的用户名查询关联的权限配置 - 将查询结果转换为复选框勾选状态 - 汇总选中权限显示在文本框中 **潜在注意事项**: 1. 硬编码的`Authorization`头存在安全风险,建议动态生成 2. 缺少错误处理逻辑(error回调) 3. 使用字符串拼接处理结果可以考虑改用`Array.join()` 4. 权限控制不能仅依赖前端验证,必须配套后端验证 5. 对`msg.ds`的数据结构有强依赖,建议增加数据校验 6. 建议使用`.prop()`代替`.attr()`操作复选框状态
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值