博主
258
258
258
258
专辑

第十节 Spring框架使用MyBatis入门

亮子 2023-10-16 05:47:47 4660 0 0 0

1、创建实体类

package com.shenmazong.zg2.pojo;

import lombok.Data;

/**
 * @author 军哥
 * @version 1.0
 * @description: 用户信息
 * @date 2023/10/15 22:12
 */

@Data
public class TbUser {
    private Integer userId;
    private String userName;
}

2、创建mapper接口

package com.shenmazong.zg2.mapper;

import com.shenmazong.zg2.pojo.TbUser;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2023/10/15 22:11
 */

public interface TbUserMapper {
    void addUser(TbUser user);
}

3、创建TbUserMapper.xml文件

图片alt

图片alt

小技巧:
可以根据 SqlMapConfig.xml 文件的内容修改

图片alt

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.shenmazong.zg2.mapper.TbUserMapper">
    <insert id="addUser" keyProperty="userId" keyColumn="user_id" useGeneratedKeys="true" parameterType="com.shenmazong.zg2.pojo.TbUser">
        insert into tb_user(user_id, user_name)
        values (#{userId}, #{userName})
    </insert>
</mapper>

4、定义service接口

package com.shenmazong.zg2.service;

import com.shenmazong.zg2.pojo.TbUser;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2023/10/15 22:16
 */

public interface TbUserService {
    TbUser addUser(String userName);
}

5、定义impl实现类

package com.shenmazong.zg2.service.impl;

import com.shenmazong.zg2.mapper.TbUserMapper;
import com.shenmazong.zg2.pojo.TbUser;
import com.shenmazong.zg2.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2023/10/15 22:17
 */

@Service
@Slf4j
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Override
    public TbUser addUser(String userName) {

        TbUser tbUser = new TbUser();
        tbUser.setUserName(userName);

        tbUserMapper.addUser(tbUser);

        return tbUser;
    }
}

6、定义控制接口

package com.shenmazong.zg2.controller;

import com.shenmazong.zg2.pojo.TbUser;
import com.shenmazong.zg2.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2023/10/15 22:15
 */

@RestController
@RequestMapping(value = "/user")
public class TbUserController {

    @Autowired
    TbUserService tbUserService;

    @PostMapping(value = "/addUser")
    public TbUser addUser(String userName) {

        return tbUserService.addUser(userName);
    }

}