一:什么是ORM
ORM(Object Relational Mapping)对象关系映射
假设有一个user表里面有俩个字段id 和name那么相应的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.启动测试一下
欧克 结束