springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

时间:2024-06-19 09:35:50

一、注解方式

  1. 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>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>

说明: springboot版本: 2.1.5.RELEASE

  1. application.properties
# mysql
spring.datasource.url=jdbc:mysql://212.64.xxx.xxx:3306/test?autoR&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3.在启动类中添加对 mapper 包扫描@MapperScan

package com.wangzaiplus.test;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter; @SpringBootApplication
@MapperScan("com.wangzaiplus.test.mapper")
public class TestApplication { public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
} /**
* 跨域
* @return
*/
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
} }

说明: springboot项目添加corsFilter解决跨域问题

也可以直接在 Mapper 类上面添加注解@Mapper

  1. mapper
package com.wangzaiplus.test.mapper;

import com.wangzaiplus.test.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType; import java.util.List; public interface UserMapper { @Select("select * from user")
@Results({
@Result(property = "username", column = "username", jdbcType = JdbcType.VARCHAR),
@Result(property = "password", column = "password")
})
List<User> selectAll(); @Select("select * from user where id = #{id}")
@Results({
@Result(property = "username", column = "username", jdbcType = JdbcType.VARCHAR),
@Result(property = "password", column = "password")
})
User selectOne(Integer id); @Insert("insert into user(username, password) values(#{username}, #{password})")
void insert(User user); @Update("update user set username=#{username}, password=#{password} where id = #{id}")
void update(User user); @Delete("delete from user where id = #{id}")
void delete(Integer id); }
  1. controller
package com.wangzaiplus.test.controller;

import com.wangzaiplus.test.pojo.User;
import com.wangzaiplus.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import java.util.List; @RestController
@RequestMapping("/user")
public class UserController { @Autowired
private UserService userService; @GetMapping("users")
public String getAll() {
List<User> users = userService.getAll();
return users.toString();
} @GetMapping("{id}")
public String getOne(@PathVariable Integer id) {
User user = userService.getOne(id);
return user + "";
} @PostMapping
public String add(User user) {
userService.add(user);
return "nice";
} @PutMapping
public String update(User user) {
userService.update(user);
return "nice";
} @DeleteMapping("{id}")
public String delete(@PathVariable Integer id) {
userService.delete(id);
return "nice";
} }

说明: restful接口风格

  1. service
package com.wangzaiplus.test.service;

import com.wangzaiplus.test.pojo.User;

import java.util.List;

public interface UserService {

    List<User> getAll();

    User getOne(Integer id);

    void add(User user);

    void update(User user);

    void delete(Integer id);

}

  1. impl
package com.wangzaiplus.test.service.impl;

import com.wangzaiplus.test.mapper.UserMapper;
import com.wangzaiplus.test.pojo.User;
import com.wangzaiplus.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper; @Override
public List<User> getAll() {
return userMapper.selectAll();
} @Override
public User getOne(Integer id) {
return userMapper.selectOne(id);
} @Override
public void add(User user) {
userMapper.insert(user);
} @Override
public void update(User user) {
userMapper.update(user);
} @Override
public void delete(Integer id) {
userMapper.delete(id);
} }

说明: 仅供示例, 逻辑严谨性暂不考虑

  1. pojo
package com.wangzaiplus.test.pojo;

import lombok.Data;

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

说明: @Data lombok

9.sql

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `unq_username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  1. 接口请求
  • add

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

  • update

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

  • delete

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

  • getOne

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

  • getAll

springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

说明: 截图请求参数id与数据库id不对应问题, 这是由于我接口文档默认值设为1或2的, 请求成功后接口管理工具自动刷新显示默认值id=1了, 所以看着好像不对, 实际没问题

以上代码均通过测试

二、xml方式

  1. pom文件<build>节点下添加
		<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>

说明: 如果不添加此节点mybatis的mapper.xml文件都会被漏掉, 会出现org.apache.ibatis.binding.BindingException Invalid bound statement (not found)异常

  1. mapper java
package com.wangzaiplus.test.mapper;

import com.wangzaiplus.test.pojo.User;

import java.util.List;

public interface UserMapper {

    List<User> selectAll();

    User selectOne(Integer id);

    void insert(User user);

    void update(User user);

    void delete(Integer id);

}

说明: 不需要@Select @Insert等注解了

  1. 新建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.wangzaiplus.test.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.wangzaiplus.test.pojo.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap> <sql id="Base_Column_List" >
id, username, password
</sql> <select id="selectAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM user
</select> <select id="selectOne" parameterType="int" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM user
WHERE id = #{id}
</select> <insert id="insert" parameterType="com.wangzaiplus.test.pojo.User">
INSERT INTO user(username, password) VALUES (#{username}, #{password})
</insert> <update id="update" parameterType="com.wangzaiplus.test.pojo.User">
UPDATE user SET
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password}
</if>
WHERE id = #{id}
</update> <delete id="delete" parameterType="int">
DELETE FROM user WHERE id =#{id}
</delete>
</mapper>

说明: 相当于将上个版本@Select @Insert注解用xml配置文件形式代替而已

  1. 其他都不需要修改

参考文章: https://www.cnblogs.com/ityouknow/p/6037431.html