赞
踩
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
本文借助Spring boot来搭建,所需要的前期准备环境准备:
CREATE TABLE `user` (
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
这里是简单创建了一个user表,只包含name和age两个字段。
<?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>3.2.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>org.example.yy</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>21</maven.compiler.source> <maven.compiler.target>21</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.3.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </pluginRepository> </pluginRepositories> </project>
这里重点引入了三个依赖:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SSMApplication {
public static void main(String[] args) {
SpringApplication.run(SSMApplication.class, args);
}
}
这里只是简单的Springboot启动类入口,没有添加其他注解。
import lombok.RequiredArgsConstructor; import org.example.ssm.entity.User; import org.example.ssm.service.UserService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController @RequiredArgsConstructor public class UserController { private final UserService userService; @GetMapping("/hello/{name}") public ResponseEntity<User> hello(@PathVariable String name) { return ResponseEntity.ok(userService.getUser(name)); } }
import lombok.RequiredArgsConstructor;
import org.example.ssm.entity.User;
import org.example.ssm.mapper.UserMapper;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class UserService {
private final UserMapper userMapper;
public User getUser(String name) {
return userMapper.findByName(name);
}
}
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.example.ssm.entity.User;
@Mapper
public interface UserMapper {
@Select("select * from user where name=#{name}")
User findByName(@Param("name") String name);
}
这里是Mybatis定义mapper的地方,mapper可以通过注解来定义,也可以通过xml来定义。
当然,这里还需要实体类User.java
import lombok.Data;
@Data
public class User {
private String name;
private int age;
}
Spring boot需要的配置文件,指定dataSource的信息:
server:
port: 9099
spring:
datasource:
url: jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC
username: root
password: Yuanyao@123
driverClassName: com.mysql.cj.jdbc.Driver
此时可以通过API访问:
➜ ~ curl http://localhost:9099/hello/tom
{"name":"tom","age":23}%
可以看到,已经可以从数据库中查询出数据了。
如果使用的mybatis-spring-boot-starter的版本是3.0.2的话,可能会遇到这个问题,导致程序无法启动。这是为什么呢?
这是因为在处理BeanDefinitions的时候,设置的attribute设置的值是beanName,而不是Class对象。
definition.setAttribute(FACTORY_BEAN_OBJECT_TYPE, beanClassName);
好在,在3.0.3这个版本中,已经修复了这个问题:
Class<?> beanClass = Resources.classForName(beanClassName);
// Attribute for MockitoPostProcessor
// https://github.com/mybatis/spring-boot-starter/issues/475
definition.setAttribute(FACTORY_BEAN_OBJECT_TYPE, beanClass);
所以解决方法很简单,只需引用新版本就好了!
当然了,也可以手动配置sqlSessionFactoryBean。
这里虽然可以使用程序了,但是有很多问题没有解决,Mybatis是如何与Spring整合的?Mybatis的SqlSession对象是如何加载的?mapper这个接口类,又是怎么被加载的?我们注解的sql语句,如果用xml文件怎么做?
挖坑不断,接下里再填。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。