SpringBoot 整合MyBatis

2019-10-17  本文已影响0人  拉提娜的爸爸

一、准备环境

1、导入pom依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2、配置数据库连接

#database
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username = root
spring.datasource.password = admin

二、使用MyBatis注解版

1、编写实体类

这里和数据库表字段一一对应就可以了,大家都知道

2、编写Mapper类(接口)

package com.me.study.springboot02mybatis.mapper;

import com.me.study.springboot02mybatis.bean.Department;
import org.apache.ibatis.annotations.*;

import java.util.List;

// @Mapper 表明这个类是一个操作数据库的mapper 也可以在项目启动类上添加
// @MapperScan("com.me.study.springboot02mybatis.mapper")
@Mapper
public interface DepartmentMapper {

    @Select("select * from department")
    List<Department> select();

    @Select("select * from department where id = #{id}")
    Department selectByPrimaryKey(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    @Insert("insert into department(department_name) values(#{departmentName})")
    int insert(Department department);

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

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

3、编写测试代码

@RestController
public class HelloConroller {

    @Autowired
    private DepartmentMapper departmentMapper;

    @GetMapping("/selectById/{id}")
    public Department select(@PathVariable("id") Integer id){
        return departmentMapper.selectByPrimaryKey(id);
    }

    @GetMapping("/insert")
    public Department insert(Department department){
        departmentMapper.insert(department);
        return department;
    }

    @GetMapping("/update")
    public Integer update(Department department){
        return departmentMapper.update(department);
    }

    @GetMapping("/delete/{id}")
    public List<Department> delete(@PathVariable("id") Integer id){
        departmentMapper.delete(id);
        return departmentMapper.select();
    }
}

4、测试运行

整合mybatis根据id查询结果

部门名成为空的原因是因为:
实体类部门属性为:departmentName
数据库表中字段为:department_name
字段与属性名称不一致Mybaits识别不到,需要启用Mybaits驼峰命名

5、给MyBaits添加属性配置

@Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                // 启用驼峰命名法
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

6、运行结果

给mybatis添加驼峰命名之后的结果

三、使用MyBatis配置文件版

1、添加MyBatis配置文件

1)添加mybatis核心配置文件
在项目resources目录下创建mapper/config文件夹,添加配置文件

<?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" />
         <!-- 打印sql日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

2)添加mybatis的sql映射文件
在mapper文件夹下存放mapper映射文件

<?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.me.study.springboot02mybatis.mapper.DepartmentMapper">
    <sql id="Base_Column_List">id,department_name</sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.Integer"
            resultType="com.me.study.springboot02mybatis.bean.Department">
        select
        <include refid="Base_Column_List"/>
        from department
        where id = #{id,jdbcType=INTEGER}
    </select>
</mapper>

2、在application,properties中添加配置

# mybatis
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.config-location=classpath:mapper/config/mybatis-config.xml
mybatis.type-aliases-package=com.me.study.springboot02mybatis.bean.Department

# database
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username = root
spring.datasource.password = admin

3、编写mapper接口

@Mapper
public interface DepartmentMapper {
    Department selectByPrimaryKey(Integer id);
}

4、编写测试代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot02MybatisApplicationTests {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Test
    public void mybatisTest(){
        Department department = departmentMapper.selectByPrimaryKey(2);
        System.out.println(department);
    }

}

5、测试结果

运行结果正确
上一篇下一篇

猜你喜欢

热点阅读