springboot配置mybatis的xml
时间: 2023-04-27 12:02:27 浏览: 75
1. 首先,在pom.xml文件中添加mybatis和mybatis-spring-boot-starter的依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
```
2. 在application.properties文件中配置mybatis的相关属性:
```
# mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
其中,mapper-locations属性指定了mapper文件的位置,type-aliases-package属性指定了实体类的包名。
3. 在mapper文件中编写SQL语句,例如:
```
<?xml version="1." encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getUserById" resultType="com.example.demo.entity.User">
select * from user where id=#{id}
</select>
</mapper>
```
其中,namespace属性指定了mapper接口的全限定名,id属性指定了SQL语句的唯一标识符,resultType属性指定了返回结果的类型。
4. 在mapper接口中定义方法,例如:
```
public interface UserMapper {
User getUserById(Integer id);
}
```
其中,方法名要与mapper文件中的id属性相同,方法参数要与SQL语句中的参数相同,返回值要与mapper文件中的resultType属性相同。
5. 在Service层中调用mapper接口的方法,例如:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
}
```
其中,通过@Autowired注解注入mapper接口的实例,然后调用其方法即可。
以上就是使用Spring Boot配置MyBatis的XML文件的步骤。