一步一步学SpringBoot(五)---SpringBoot整合Mybatis进行简单的增删改查

本文介绍了如何在SpringBoot项目中整合Mybatis进行基本的增删改查操作。首先,确认引入相关依赖,然后通过MybatisGenerator自动生成User实体类、UserMapper接口和Sql配置文件。在UserMapper.java中手动添加注解。接着配置application.yml,设置Mapper.xml的路径。进一步,创建UserService和UserController,实现根据id查询的功能。最后,启动服务,通过访问特定URL测试查询功能是否成功。

在pom文件引入依赖

前面已经引入了这些依赖,再确定一下

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

生成代码

在(二)里面就示范用MybatisGenerator生成代码

entity类User.java

package com.test.springbm.entity;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;

    private String name;

    private String password;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Mapper接口UserMapper.java

package com.test.springbm.mapper;

import com.test.springbm.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
*在Mapper接口上进行以下注解
*/
@Mapper
@Repository
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

如果不进行@Repository注解,在service层的时候会提示UserMapper无法@Autowired

Mapper的Sql配置文件UserMapper.xml

<?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.test.springbm.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.test.springbm.entity.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <sql id="Base_Column_List">
    id, `name`, `password`
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.test.springbm.entity.User">
    insert into user (id, `name`, `password`
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.test.springbm.entity.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        `name`,
      </if>
      <if test="password != null">
        `password`,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.test.springbm.entity.User">
    update user
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        `password` = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.test.springbm.entity.User">
    update user
    set `name` = #{name,jdbcType=VARCHAR},
      `password` = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

注意不要重复生成文件,我就是在测试的时候重复生成了UserMapper.xml,导致

XML fragments parsed from previous mappers already contains value for com.test.springbm.mapper.UserMapper.Base_Column_List

错误
解决办法是删除重复项

以上三个文件是自动生成的,当然UserMapper.java里的注解需要自己手动加上

进行Mybatis配置

这里我使用的是application.yml,当然你也可以使用*.properties文件,效果一样

贴上我们的application.yml代码

# Mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  # logging.level.yourdaoclasspackagename=debug
  # mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  # 两种方式的效果是一样的,但是上面一种可以指定某个包下的SQL打印出来,下面这个会全部的都会打印出来
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

mapper-locations选择你的*Mapper.xml相对路径

接下来我们编写service

新建UserService.java

package com.test.springbm.service;

import com.test.springbm.entity.User;
import com.test.springbm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    private UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper){
        this.userMapper = userMapper;
    }

    public User selectUserById(Integer id) {
        return this.userMapper.selectByPrimaryKey(id);
    }

}

我这里就简单的写个根据id查询,像增删改和查询列表你们可以自己试着实现

使用@Transactional(rollbackFor = Exception.class)注解是因为不用的话运行的时候会提示

SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@99362df] was not registered for synchronization because synchronization is not active

JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@55142dc9] will not be managed by Spring

当然对结果没有影响,你可以选择去掉,但作为一个强迫症患者,知道了解决的办法就一定要用上

最后编写我们的controller

新建UserController.java

package com.test.springbm.controller;

import com.test.springbm.entity.User;
import com.test.springbm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/user", method = {RequestMethod.GET,RequestMethod.POST})
public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }

    @RequestMapping(value = "/select")
    public User selectByUserId(Integer id){
        return this.userService.selectUserById(id);
    }
}

最后启动服务

输入localhost:8080/user/select?id=1,如果出现数据,那么恭喜成功

至此结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值