springboot集成mybatis的配置是什么

小億
82
2024-01-16 19:53:04

在Spring Boot中集成MyBatis的配置主要包括以下幾個(gè)步驟:

  1. 引入相關(guān)依賴:在pom.xml文件中添加MyBatis和數(shù)據(jù)庫(kù)驅(qū)動(dòng)的依賴,例如:
<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>
  1. 配置數(shù)據(jù)源:在application.propertiesapplication.yml文件中配置數(shù)據(jù)庫(kù)連接信息,例如:
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
  1. 創(chuàng)建Mapper接口和XML文件:創(chuàng)建Mapper接口,定義數(shù)據(jù)庫(kù)操作方法;創(chuàng)建對(duì)應(yīng)的XML文件,編寫(xiě)SQL語(yǔ)句。例如:
@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語(yǔ)句 -->
</mapper>
  1. 配置MyBatis:創(chuàng)建MyBatisConfig類(lèi),使用@MapperScan注解指定Mapper接口的掃描路徑。例如:
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
}
  1. 使用Mapper接口:在需要使用數(shù)據(jù)庫(kù)操作的地方,注入對(duì)應(yīng)的Mapper接口,并調(diào)用方法。例如:
@Autowired
private UserMapper userMapper;

public List<User> getAllUsers() {
    return userMapper.getAllUsers();
}

以上就是Spring Boot集成MyBatis的基本配置步驟,具體根據(jù)項(xiàng)目需求可以進(jìn)行相應(yīng)調(diào)整和擴(kuò)展。

0