幽兰生空谷
--绝世独自开

SpringBoot操作数据库SpringData(三)-整合MyBatis

整合MyBatis

官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfifigure/

Maven仓库地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.2.0

整合测试

1、导入 MyBatis 所需要的依赖 

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

2、配置数据库连接信息(不变)

spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource #自定义数据源
    #SpringBoot 默认配置是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    druid:
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
      #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
      #则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
      filters: stat,wall,log4j
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3、测试数据库是否连接成功!

4、创建实体类,导入 Lombok!

Department.java

package com.itheibai.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data //get、set方法
@NoArgsConstructor //无参构造函数
@AllArgsConstructor //所有带参构造函数
public class Department {
    private Integer id;
    private String departmentName;
}

5、创建mapper目录以及对应的 Mapper 接口

DepartmentMapper.java

package com.itheibai.mapper;
import com.itheibai.pojo.Department;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//@Mapper: 表示本类是一个 MyBatis 的Mapper
@Mapper
@Repository
public interface DepartmentMapper {
    //获取所有部门信息
    List<Department> getDepartments();
    //通过id获得部门
    Department getDepartment(Integer id);
}

6、对应的Mapper映射文件 

mybatis中文文档https://mybatis.org/mybatis-3/zh/getting-started.html

DepartmentMapper.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.itheibai.mapper.DepartmentMapper">
    <select id="getDepartments" resultType="com.itheibai.pojo.Department">
        select * from Department
    </select>
    <select id="getDepartment" resultType="Department" parameterType="int">
        select * from department where id = #{id}
    </select>
</mapper>

如果配置了别名报红,可能是开启了MyBatis插件,可以禁用或使用全限定名即可。

7、maven配置资源过滤问题

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>

既然已经提供了 myBatis 的映射配置文件,自然要告诉 spring boot 这些文件的位置 

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.itheibai.pojo
  configuration:
    map-underscore-to-camel-case: true #开启驼峰命名

8、编写部门的 DepartmentController 进行测试!** 

package com.itheibai.controller;
import com.itheibai.mapper.DepartmentMapper;
import com.itheibai.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class DepartmentController {
    @Autowired
    DepartmentMapper departmentMapper;
    //查询全部部门
    @GetMapping("/getDepartments")
    public List<Department> getDepartments(){
        return departmentMapper.getDepartments();
    }
    //根据id查询部门,@PathVariable接收请求路径中占位符的值,
    //可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中
    @GetMapping("/getDepartment/{id}")
    public Department getDepartment(@PathVariable("id")Integer id){
        return departmentMapper.getDepartment(id);
    }
}

启动项目访问进行测试!

我们增加一个员工类再测试下,为之后做准备

1、新建一个pojo类 Employee ; 

package com.itheibai.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private Integer id; 
    private String lastName; 
    private String email; 
    //1 male, 0 female 
    private Integer gender; 
    private Integer department; 
    private Date birth; 
    private Department eDepartment; // 冗余设计
}

2、新建一个 EmployeeMapper 接口 

package com.itheibai.mapper;
import com.itheibai.pojo.Employee;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface EmployeeMapper {
    // 获取所有员工信息 
    List<Employee> getEmployees(); 
    // 新增一个员工 
    int save(Employee employee); 
    // 通过id获得员工信息 
    Employee get(Integer id); 
    // 通过id删除员工
    int delete(Integer id);
}

3、编写 EmployeeMapper.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.itheibai.mapper.EmployeeMapper">
    <resultMap id="EmployeeMap" type="Employee">
        <id property="id" column="eid"/>
        <result property="lastName" column="last_name"/>
        <result property="email" column="email"/>
        <result property="gender" column="gender"/>
        <result property="birth" column="birth"/>
        <association property="eDepartment" javaType="Department">
            <id property="id" column="did"/>
            <result property="departmentName" column="dname"/>
        </association>
    </resultMap>
    <select id="getEmployees" resultMap="EmployeeMap">
        select e.id as eid,last_name,email,gender,birth,d.id as did,d.department_name as dname
        from department d,employee e
        where d.id = e.department
    </select>
    <insert id="save" parameterType="Employee">
        insert into employee (last_name,email,gender,department,birth)
        values (#{lastName},#{email},#{gender},#{department},#{birth});
    </insert>
    <select id="get" resultType="Employee">
        select * from employee where id = #{id}
    </select>
    <delete id="delete" parameterType="int">
        delete from employee where id = #{id}
    </delete>
</mapper>

4、编写EmployeeController类进行测试

package com.itheibai.controller;
import com.itheibai.mapper.EmployeeMapper;
import com.itheibai.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
@RestController
public class EmployeeController {
    @Autowired
    EmployeeMapper employeeMapper;
    // 获取所有员工信息
    @GetMapping("/getEmployees")
    public List<Employee> getEmployees(){
        return employeeMapper.getEmployees();
    }
    @GetMapping("/save") 
    public int save(){ 
        Employee employee = new Employee(); 
        employee.setLastName("kuangshen"); 
        employee.setEmail("qinjiang@qq.com"); 
        employee.setGender(1); 
        employee.setDepartment(101);
        employee.setBirth(new Date()); 
        return employeeMapper.save(employee); 
    }

    // 通过id获得员工信息 
    @GetMapping("/get/{id}") 
    public Employee get(@PathVariable("id") Integer id){ 
        return employeeMapper.get(id); 
    }

    // 通过id删除员工 
    @GetMapping("/delete/{id}") 
    public int delete(@PathVariable("id") Integer id){ 
        return employeeMapper.delete(id); 
    }
}

测试结果完成,搞定收工

赞(5) 打赏
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《SpringBoot操作数据库SpringData(三)-整合MyBatis》
文章链接:https://www.itheibai.com/archives/643
免责声明:根据《计算机软件保护条例》第十七条规定“为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。”您需知晓本站所有内容资源均来源于网络,仅供用户交流学习与研究使用,版权归属原版权方所有,版权争议与本站无关,用户本人下载后不能用作商业或非法用途,需在24个小时之内从您的电脑中彻底删除上述内容,否则后果均由用户承担责任;如果您访问和下载此文件,表示您同意只将此文件用于参考、学习而非其他用途,否则一切后果请您自行承担,如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
本站是非经营性个人站点,所有软件信息均来自网络,所有资源仅供学习参考研究目的,并不贩卖软件,不存在任何商业目的及用途,网站会员捐赠是您喜欢本站而产生的赞助支持行为,仅为维持服务器的开支与维护,全凭自愿无任何强求。

评论 抢沙发

评论前必须登录!

 

养成“打赏”的好习惯,从我做起!

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册