一、注解方式
- pom
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
mysql
mysql-connector-java
org.projectlombok
lombok
1.16.10
说明: springboot版本: 2.1.5.RELEASE
- 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
- 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 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);
}
- 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 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接口风格
- service
package com.wangzaiplus.test.service;
import com.wangzaiplus.test.pojo.User;
import java.util.List;
public interface UserService {
List getAll();
User getOne(Integer id);
void add(User user);
void update(User user);
void delete(Integer id);
}
- 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 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);
}
}
说明: 仅供示例, 逻辑严谨性暂不考虑
- 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;
- 接口请求
- add
- update
- delete
- getOne
- getAll
说明: 截图请求参数id与数据库id不对应问题, 这是由于我接口文档默认值设为1或2的, 请求成功后接口管理工具自动刷新显示默认值id=1了, 所以看着好像不对, 实际没问题
以上代码均通过测试
二、xml方式
- pom文件
节点下添加
src/main/java
**/*.xml
说明: 如果不添加此节点mybatis的mapper.xml文件都会被漏掉, 会出现
org.apache.ibatis.binding.BindingException Invalid bound statement (not found)
异常
- mapper java
package com.wangzaiplus.test.mapper;
import com.wangzaiplus.test.pojo.User;
import java.util.List;
public interface UserMapper {
List selectAll();
User selectOne(Integer id);
void insert(User user);
void update(User user);
void delete(Integer id);
}
说明: 不需要
@Select
@Insert
等注解了
- 新建
UserMapper.xml
文件
id, username, password
INSERT INTO user(username, password) VALUES (#{username}, #{password})
UPDATE user SET
username = #{username},
password = #{password}
WHERE id = #{id}
DELETE FROM user WHERE id =#{id}
说明: 相当于将上个版本
@Select
@Insert
注解用xml配置文件形式代替而已
- 其他都不需要修改
参考文章: https://www.cnblogs.com/ityouknow/p/6037431.html