在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的基本配置步驟,具體根據項目需求可以進行相應調整和擴展。