在Spring Boot中集成MyBatis的配置主要包括以下几个步骤:
pom.xml
文件中添加MyBatis和数据库驱动的依赖,例如:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.properties
或application.yml
文件中配置数据库连接信息,例如:spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
@Repository
public interface UserMapper {
List<User> getAllUsers();
User getUserById(int id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="getAllUsers" resultType="com.example.model.User">
select * from user
</select>
<!-- 其他SQL语句 -->
</mapper>
MyBatisConfig
类,使用@MapperScan
注解指定Mapper接口的扫描路径。例如:@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
}
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
以上就是Spring Boot集成MyBatis的基本配置步骤,具体根据项目需求可以进行相应调整和扩展。