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接口和映射文件來操作數據庫。