SpringBoot学习之整合Mybatis

一:什么是ORM
ORM(Object Relational Mapping)对象关系映射

假设有一个user表里面有俩个字段idname那么相应的Java程序中的User类就有这样的两个属性
在这里插入图片描述在这里插入图片描述
MyBatis就是对应的框架

二:SpringBoot中使用MyBatis

官方文档

1.添加依赖到pom.xml
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>
2.创建Mapper接口src/main/java/mapper/UserMapper
package hello.mapper;

import hello.service.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user WHERE id = #{id}")
    User findUserById(@Param("id") Integer id);

}
3.更新UserService注入mapper
package hello.service;

import hello.mapper.UserMapper;

import javax.inject.Inject;

public class UserService {
    private static UserMapper userMapper;


    @Inject
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public static User getUserById(Integer id) {
        return userMapper.findUserById(id);
    }

}

4.创建数据源配置文件src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/blog?serverTimezone=GMT%2B8
spring.datasource.username=Blog
spring.datasource.password=Mall@123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

说明:我的MySQL是8.0,相关参数请根据自己需要配置

5.配置MySQL加载驱动pom.xml
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.14</version>
        </dependency>
6.编写Controller src/main/java/hello/HelloController.java
package hello;

import hello.service.User;
import hello.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
   
    private UserService userService;

    public HelloController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/")
    public User index() {
        return this.userService.getUserById(1);
    }

}

7:更新一下JavaConfiguration
package hello.configuration;

import hello.mapper.UserMapper;
import hello.service.OrderService;
import hello.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfiguration {
    @Bean
    public OrderService orderService(UserService userService) {
        return new OrderService(userService);
    }

    @Bean
    public UserService userService(UserMapper userMapper) {
        return new UserService(userMapper);
    }
}

8.启动测试一下

在这里插入图片描述
欧克 结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值