springboot的mapper配置模板
时间: 2023-07-01 08:26:39 浏览: 216
在Spring Boot中使用MyBatis框架进行数据库操作时,需要进行Mapper XML配置和Mapper接口的配置。下面是一个简单的Mapper配置模板:
1. 首先需要在application.properties文件中配置MyBatis的相关属性:
```properties
# 数据库连接配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
# MyBatis配置
mybatis.type-aliases-package=com.example.domain
mybatis.mapper-locations=classpath:mapper/*.xml
```
2. 在mapper文件夹下创建相应的Mapper接口,例如:
```java
public interface UserMapper {
User selectUserById(int id);
}
```
3. 创建对应的Mapper XML文件,例如:
```xml
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.example.domain.User">
select * from user where id = #{id}
</select>
</mapper>
```
4. 在启动类(即带有@SpringBootApplication注解的类)中添加@MapperScan注解,指定扫描Mapper接口所在的包:
```java
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
这样就完成了Mapper配置的基本步骤。在使用Mapper接口时,可以直接注入Mapper接口进行数据库操作,无需编写实现类。例如:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
```
阅读全文