What is the configuration for integrating MyBatis with Spring Boot?
The main steps for integrating MyBatis configuration in Spring Boot include the following:
- This is the pom.xml file.
<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>
- properties file for the application
- config file named application.yaml
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
- Generate Mapper interface and XML file: Establish a Mapper interface to define database operation methods; set up the corresponding XML file to write SQL statements. For example:
@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>
- Configuration file for MyBatis
- Scan for mappers
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
}
- Utilize the Mapper interface: inject the corresponding Mapper interface in the location where database operations are needed, and then call the methods. For example:
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
The above are the basic configuration steps for integrating MyBatis with Spring Boot. Specific adjustments and extensions can be made according to the project requirements.