从零开始学习SpringBoot

SpringBoot - myBatis

2018-05-28  本文已影响57人  BzCoder

一.简介

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

二.配置

1.首先引入MAVEN以及JDBC配置

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

JDBC

spring:
  datasource:
    password: 123456
    username: root
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.15.128:3306/yourdatabase

2.参数配置

a.注解配置

package com.example.jdbc.mapper;
import com.example.jdbc.bean.Department;
import org.apache.ibatis.annotations.*;

/**
 * @author BaoZhou
 * @date 2018/5/28
 */
@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是为了获取自增ID
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int inserDept(Department department);

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

写好以上配置后,代码中使用如下:

    @Autowired
    DepartmentMapper departmentMapper;

    @ResponseBody
    @GetMapping("/getDept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id)
    {
        return departmentMapper.getDeptById(id);
    }

    @ResponseBody
    @GetMapping("/getDept")
    public Department insertDepartment(Department department)
    {
         departmentMapper.inserDept(department);
        return department;
    }

配置类

package com.example.jdbc.config;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;

/**
 * @author BaoZhou
 * @date 2018/5/28
 */
@MapperScan(value = "com.example.jdbc.mapper") //可以使用mapperScan批量扫描所有mapper接口
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {

            @Override
            public void customize(Configuration configuration) {
                //开启驼峰命名法
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

直接运行即可生效。


b.配置文件配置

首先可以参考mybatis官方文档:http://www.mybatis.org/mybatis-3/zh/index.html
全局配置文件:

<?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>
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</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.example.jdbc.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.example.jdbc.bean.Employee">
    select * from employee where id=#{id}
  </select>

    <insert id="insertEmp">
        INSERT INTO employee(lastName,email,gender,d_id)VALUES (#{lastName},#{email},#{gender},#{d_id})
    </insert>
</mapper>

application配置文件:

mybatis:
  #全局配置文件地址
  config-location: classpath:mybatis/mybatis-config.xml
  #指定文件配置地址
  mapper-locations: classpath:mybatis/mapper/*.xml

mapper文件:

package com.example.jdbc.mapper;

import com.example.jdbc.bean.Employee;

/**
 * @author BaoZhou
 * @date 2018/5/28
 */
//需要扫描,由于我们配置文件里已经添加了扫描,所以此处不加Mapper注解
public interface EmployeeMapper {
    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

使用:

 @Autowired
    EmployeeMapper employeeMapper;

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

    @ResponseBody
    @GetMapping("/getEmp")
    public Employee insertEmp(Employee employee)
    {
        employeeMapper.insertEmp(employee);
        return employee;
    }


三.结束

有关于配置myBatis的简单使用就到这里了。主要就是两种方式,一种是配置文件配置,一种是注解方式。两种都可以。

上一篇下一篇

猜你喜欢

热点阅读