SpringBoot--整合Mybatis

1、添加Mybatis依赖

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

2、创建实体对象

package com.example.demo.entity;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String password;


}

3、添加mybatis配置

# 注意注意
mybatis:
  #mapper-locations: classpath:com/battcn/mapper/*.xml
  mapper-locations: classpath:mapper/*.xml        #这种方式需要自己在resources目录下创建mapper目录然后存放xml
  type-aliases-package: com.example.demo.entity
# 驼峰命名规范 如:数据库字段是  order_id 那么 实体字段就要写成 orderId
  configuration:
    map-underscore-to-camel-case: true

4、创建Mybatis接口及对应mapper配置

此处说明一下,对于UserMapper.java列举了两种配置方式,第一种是直接使用注解的方式进行处理,第二种是使用xml的方式配置。

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {

    @Select("select * from t_user where username = #{username}")
    List<User> selectByuserName(@Param("username") String username);

    int insert(User user);
}
<?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.demo.mapper.UserMapper">

    <insert id="insert" parameterType="com.example.demo.entity.User">
    INSERT INTO `t_user`(`username`,`password`) VALUES (#{username},#{password})
  </insert>

</mapper>

5、创建Controller、Service

@ResponseBody
    @PostMapping(value ="/mybatis1")
    @ApiOperation(value="整合mybatis测试")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "username", value = "用户ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "password", value = "密码", required = true, dataType = "String")
    })
    public String test2(String username, String password){
        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        return userService.AddUserMybatis(u) + "";
    }

    @ResponseBody
    @PostMapping(value ="/mybatis2")
    @ApiOperation(value="整合mybatis测试")
    @ApiImplicitParams(@ApiImplicitParam(paramType="query", name = "username", value = "用户ID", required = true, dataType = "String"))
    public String test3(String username){
        return JSON.toJSONString(userService.selectByUsername(username));
    }
    public int AddUserMybatis(User user){
        return userMapper.insert(user);
    }

    public List<User> selectByUsername(String username) {
        return userMapper.selectByuserName(username);
    }

6、测试

原文地址:https://www.cnblogs.com/liconglong/p/11691817.html