Springboot Mybatis 简单demo
实体类entity
User
package bx.springChart.mybatisDemo.entity;
import lombok.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class User implements Serializable {
private Long id;
private String username;
private String password;
private int userId;
private int note;
}
BTW:使用了Lombok自动生成setter等
UserMapper接口
(本人理解可以视为DAO)
package bx.springChart.mybatisDemo.mapper;
import ...
//@Mapper 由于在Application中存在MapperScan所以这里可以不用添加
// 指定这是一个操作数据库的mapper
public interface UserMapper {
List<User> findAll();
List<User> findAllTwo();
User findUserById(int uid);
}
UserService接口
package bx.springChart.mybatisDemo.service;
import ...
public interface UserService {
List<User> findAll();
List<User> findAllTwo();
User findUserById(int id);
}
UserServiceImpl
package bx.springChart.mybatisDemo.serviceImpl;
import ...
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public List<User> findAllTwo() {
return userMapper.findAllTwo();
}
@Override
public User findUserById(int uid) {
return userMapper.findUserById(uid);
}
}
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="bx.springChart.mybatisDemo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="bx.springChart.mybatisDemo.entity.User">
<result column="id" jdbcType="INTEGER" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
</resultMap>
<resultMap id="ResultMap2" type="bx.springChart.mybatisDemo.entity.User">
<result column="id" jdbcType="INTEGER" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="note" jdbcType="VARCHAR" property="note"/>
<result column="userid" jdbcType="INTEGER" property="userId"/>
</resultMap>
<select id="findAll" resultMap="BaseResultMap">
SELECT * FROM tb_user
</select>
<select id="findAllTwo" resultMap="ResultMap2">
SELECT * FROM tb_user
</select>
<select id="findUserById" resultMap="ResultMap2" >
SELECT * FROM tb_user WHERE userid = #{uid}
</select>
</mapper>
applicaition.yml
server:
port: 8081
spring:
#数据库连接配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/echartdemoone?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
#mybatis的相关配置
mybatis:
#mapper配置文件
mapper-locations: classpath:mapper/*.xml
#此配置的功能是UserMapper.xml中type可以简写
#type-aliases-package: bx.springChart.mybatisDemo.entity
#configuration:
#开启驼峰命名
#此配置的功能是自动对应,就是代替UserMapper.xml中的resultMap
# map-underscore-to-camel-case: true
#此配置的功能是禁用Mybatis自动映射
configuration:
auto-mapping-behavior: NONE
#LOG输出SQL
logging:
level:
bx:
springChart:
mybatisDemo: debug
UserController
package bx.springChart.mybatisDemo.controller;
import ...
@RestController
@RequestMapping("/mybatis")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public List<User> findAll(){
return userService.findAll();
}
@RequestMapping("/find")
public List<User> findAllTwo(){
return userService.findAllTwo();
}
@RequestMapping("user/{uid}")
public User findUserById(@PathVariable int uid){
return userService.findUserById(uid);
}
}
MybatisApplication
package bx.springChart.mybatisDemo;
import ...
@SpringBootApplication
@MapperScan("bx.springChart.mybatisDemo.mapper")//使用MapperScan批量扫描所有的Mapper接口;
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
DDL&SQL
create table tb_user
(
id int not null
primary key,
username varchar(255) null,
password varchar(255) null,
userid int(16) null,
note varchar(45) null
)
charset = utf8;
INSERT INTO echartdemoone.tb_user (id, username, password, userid, note) VALUES (1, '老王', '老王的密码', 1, '001');
INSERT INTO echartdemoone.tb_user (id, username, password, userid, note) VALUES (2, 'Mr.laoli', 'UnknownCode', 2, '2');
注意事项
接口UserMapper
需要使用@Mapper注解,不然SpringBoot无法扫描
编写在resources文件中创建 mapper/UserMapper.xml文件
UserMapper.xml
namespace中需要与使用@Mapper的接口对应
UserMapper.xml文件名称必须与使用@Mapper的接口一致
标签中的id必须与@Mapper的接口中的方法名一致,且参数一致
UserServiceImpl
需要在接口实现类中使用@Service注解,才能被SpringBoot扫描
UserController
Controller中使用@Authwired注入
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>geektime.spring.hello</groupId>
<artifactId>mybatis-spring-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis-spring-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
程序运行
特殊错误
Could not autowire. No beans of ‘UserMapper’ type found
这其实不是一个错误,有网友说这是一个IDEA的BUG
即使不处理程序也可以正常运行,但可以解决
网页中返回结果
@Mapper与@Repository
@Mapper和@Repository的区别
1.相同点
@Mapper和@Repository都是作用在dao层接口,使得其生成代理对象bean,交给spring 容器管理
对于mybatis来说,都可以不用写mapper.xml文件
2.不同点
@Mapper不需要配置扫描地址,可以单独使用,如果有多个mapper文件的话,可以在项目启动类中加入@MapperScan(“mapper文件所在包”),这样就不需要每个mapper文件都加@Mapper注解了
@Repository不可以单独使用,否则会报错误