Spring Boot与MyBatis集成使用主要有以下几个步骤:
pom.xml
文件中添加MyBatis和Spring Boot相关的依赖,例如:<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
application.properties
或application.yml
文件中配置数据源信息,例如:spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
}
@Mapper
public interface UserMapper {
User getUserById(Long id);
}
<select id="getUserById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
}
通过以上步骤,就可以实现Spring Boot与MyBatis的集成使用,通过Mapper接口和映射文件来操作数据库。