SpringMVC整合Mybatis

SpringMVC整合Mybatis

1、导入依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.22</version>
</dependency>

2、编写配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 填写你数据库的url、登录名、密码和数据库名
    url: jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
mybatis:
  type-aliases-package: com.chen.springboot01.pojo  # 设置别名
  mapper-locations: classpath:mybatis/*.xml # mapper映射目录

3、编写功能代码

  • 在启动类上添加注解,表示mapper接口所在位置
@SpringBootApplication
//@MapperScan("com.chen.springboot01.mapper")
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}
  • 定义mapper接口,如果不在MyApplication启动类上添加@MapperScan,必须在UserMapper接口上添加@Mapper注解。
//@Mapper
public interface UserMapper {
    List<User> selectAll();
}
  • 定义mapper.xml文件,在resource下新建mybatis文件夹,mapper.xml文件名没有要求,不需要和接口名完全对应,是根据namespace去找接口。但是最好还是和接口名字保持一致
<?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.chen.springboot01.mapper.UserMapper">
    <select id="selectAll" resultType="user">
        select * from user
    </select>
</mapper>
  • 编写controller层代码
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("findAll")
    @ResponseBody
    public List<User> findAll(){
        return userService.findAll();
    }
}
  • 编写service层代码
// 接口
@Service
public interface UserService {
    List<User> findAll();
}
// 类
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }
}

注意: idea中往往会误报代码错误,如果我们确定代码无问题,可以通过降低idea检查代码的严格程度来消除报错。
快捷键: ctrl+alt+shift+h
这是一张很好的图


持续更新,如果错误,欢迎大家指出,共同学习...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个小坑货

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值