1. MyBatis简介
MyBatis是一款优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的工作。MyBatis可以让我们将这些工作封装在映射文件中,通过简单的XML配置和注解就可以实现数据库的CRUD操作。
2. MyBatis搭建环境
2.1 创建Maven项目
- 打开IDEA,创建一个新的Maven项目。
- 添加以下依赖到
pom.xml文件中:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
</dependencies>
2.2 配置数据库
- 在
src/main/resources目录下创建database.properties文件,配置数据库信息:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_example?useSSL=false&serverTimezone=UTC
username=root
password=root
- 创建一个名为
mybatis_example的数据库,并创建一个名为user的表:
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`age` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3. MyBatis核心配置
3.1 创建MyBatis配置文件
在src/main/resources目录下创建mybatis-config.xml文件,配置MyBatis环境:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_example?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3.2 创建实体类
在com.example包下创建User类,对应数据库中的user表:
package com.example;
public class User {
private Integer id;
private String name;
private Integer age;
// Getters and Setters
}
3.3 创建Mapper接口
在com.example.mapper包下创建UserMapper接口,定义CRUD操作:
package com.example.mapper;
import com.example.User;
public interface UserMapper {
void insertUser(User user);
User selectUserById(Integer id);
void updateUser(User user);
void deleteUser(Integer id);
}
4. MyBatis映射文件
在com/example/mapper包下创建UserMapper.xml文件,定义SQL映射:
<?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.example.mapper.UserMapper">
<insert id="insertUser">
INSERT INTO `user` (`name`, `age`) VALUES (#{name}, #{age})
</insert>
<select id="selectUserById" resultType="User">
SELECT `id`, `name`, `age` FROM `user` WHERE `id` = #{id}
</select>
<update id="updateUser">
UPDATE `user` SET `name` = #{name}, `age` = #{age} WHERE `id` = #{id}
</update>
<delete id="deleteUser">
DELETE FROM `user` WHERE `id` = #{id}
</delete>
</mapper>
5. MyBatis使用示例
5.1 配置Spring集成
在pom.xml文件中添加Spring集成依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
在application.properties文件中配置MyBatis相关参数:
mybatis.type-aliases-package=com.example
mybatis.mapper-locations=classpath:mapper/*.xml
在Spring Boot的主类上添加@MapperScan注解,扫描Mapper接口:
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyBatisApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisApplication.class, args);
}
}
5.2 使用MyBatis
在Spring Boot项目中,可以通过@Autowired注解注入Mapper接口,然后进行数据库操作:
package com.example;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyBatisApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisApplication.class, args);
}
}
@Controller
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/insert")
public String insertUser() {
User user = new User();
user.setName("张三");
user.setAge(20);
userMapper.insertUser(user);
return "success";
}
@GetMapping("/select")
public String selectUser() {
User user = userMapper.selectUserById(1);
System.out.println(user.getName() + " " + user.getAge());
return "success";
}
@GetMapping("/update")
public String updateUser() {
User user = new User();
user.setId(1);
user.setName("李四");
user.setAge(21);
userMapper.updateUser(user);
return "success";
}
@GetMapping("/delete")
public String deleteUser() {
userMapper.deleteUser(1);
return "success";
}
}
这样,我们就完成了MyBatis的入门和实践。希望这份指南能帮助你更好地理解和使用MyBatis。
