SpringBoot结合MyBatis 【超详细】
在Spring Boot中配合MyBatis进行数据库操作,你需要做以下几个步骤:
- 添加依赖:在
pom.xml
中添加Spring Boot Starter和MyBatis的依赖。
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- 数据库驱动,例如MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置数据库和MyBatis:在
application.properties
或application.yml
中配置数据库和MyBatis。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
- 创建Mapper接口和XML映射文件:
// UserMapper.java
package com.yourpackage.mapper;
public interface UserMapper {
User selectUserById(int id);
}
<!-- UserMapper.xml -->
<?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.yourpackage.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.yourpackage.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 创建Service和Service实现类:
// UserService.java
package com.yourpackage.service;
public interface UserService {
User getUserById(int id);
}
// UserServiceImpl.java
package com.yourpackage.service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
评论已关闭