Spring Boot2集成MyBatis

Spring Boot版本:2.0.6.RELEASE。
源代码:https://github.com/wu-boy/parker.git parker-mybatis模块

SpringBoot2集成MyBatis可以通过引入mybatis-spring-boot-starter来实现。mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解解决一切问题,一种是简化后的老传统,本人倾向于使用后者。

项目架构可以直接看源代码,这里捡主要内容说。

application.yml配置如下

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://127.0.0.1:5432/test
    username: postgres
    password: postgres
mybatis:
  type-aliases-package: com.wu.parker.mybatis
  mapper-locations: classpath:mybatis/*.xml
  configuration:
    cache-enabled: true
    auto-mapping-behavior: FULL
    default-executor-type: REUSE
    map-underscore-to-camel-case: true
    lazy-loading-enabled: true
    aggressive-lazy-loading: false
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

新建Mapper

package com.wu.parker.mybatis.dao;

import com.wu.parker.mybatis.po.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author: wusq
 * @date: 2018/11/26
 */
@Mapper
public interface UserMapper {

    int save(User user);
}

新建UserMapper.xml

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wu.parker.mybatis.dao.UserMapper">

    <insert id="save" parameterType="user">
        insert into user_test(id,username,password)values(#{id},#{username},#{password})
    </insert>

</mapper>

Mapper接口里的方法名称和xml里的id要对应起来。

测试类

package com.wu.parker.mybatis.test;

import com.wu.parker.mybatis.dao.UserMapper;
import com.wu.parker.mybatis.po.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author: wusq
 * @date: 2018/11/26
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testSave() throws Exception {
        User user = new User();
        user.setId("1");
        user.setUsername("admin");
        user.setPassword("admin");
        System.out.println(userMapper.save(user));
    }
}

参考资料:
1、springboot(六):如何优雅的使用mybatis
2、XML映射配置文件

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值