一、注解方式
- 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
- 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<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);
}
- 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接口風格
- 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);
}
- 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);
}
}
說明: 僅供示例, 邏輯嚴謹性暫不考慮
- 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
說明: 截圖請求參數(shù)id與數(shù)據(jù)庫id不對應(yīng)問題, 這是由于我接口文檔默認值設(shè)為1或2的, 請求成功后接口管理工具自動刷新顯示默認值id=1了, 所以看著好像不對, 實際沒問題
以上代碼均通過測試
二够挂、xml方式
- pom文件
<build>
節(jié)點下添加
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
說明: 如果不添加此節(jié)點mybatis的mapper.xml文件都會被漏掉, 會出現(xiàn)
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<User> selectAll();
User selectOne(Integer id);
void insert(User user);
void update(User user);
void delete(Integer id);
}
說明: 不需要
@Select
@Insert
等注解了
- 新建
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配置文件形式代替而已
- 其他都不需要修改