Spring boot + Mybatis 使用 @Mapper 或 @MapperScan 执行SQL语句
在Spring Boot项目中使用MyBatis时,可以通过@Mapper
或@MapperScan
来指定Mapper接口。
- 使用
@Mapper
注解:直接在每个Mapper接口上添加@Mapper
注解。
@Mapper
public interface UserMapper {
User selectUserById(int id);
}
- 使用
@MapperScan
注解:在Spring Boot启动类或配置类上添加@MapperScan
注解,指定需要扫描的Mapper接口所在的包路径。
@SpringBootApplication
@MapperScan("com.example.project.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在上述例子中,无论你选择@Mapper
还是@MapperScan
,最终你都可以在Service层通过注入Mapper接口来执行SQL语句。
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
确保你的项目中已经添加了MyBatis和MyBatis-Spring-Boot-Starter依赖。
<!-- 在pom.xml中添加MyBatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
评论已关闭