Spring boot + Mybatis 使用 @Mapper 或 @MapperScan 执行SQL语句

@Mapper 是 MyBatis-Spring 集成库中的一个注解,用于标识一个接口作为 MyBatis 的 Mapper 接口。当你使用 MyBatis 与 Spring 框架一起时,你可以使用这个注解来自动扫描和注册 Mapper 接口,这样 Spring 容器就可以自动管理这些 Mapper 接口的实现,而无需手动配置。

这里是一个简单的例子,展示如何使用 @Mapper 注解:

import org.apache.ibatis.annotations.Mapper;  
import org.apache.ibatis.annotations.Select;  
  
@Mapper  
public interface UserMapper {  
  
    @Select("SELECT * FROM users WHERE id = #{id}")  
    User getUserById(int id);  
  
    // 还可以定义其他CRUD操作的方法  
}

在上面的例子中,UserMapper 接口使用 @Mapper 注解标识,这意味着 MyBatis 会为这个接口创建一个代理实现,这个实现会处理与数据库相关的操作。@Select 注解用于指定 SQL 查询语句。

如果你有很多 Mapper 接口,并且想要避免在每个接口上都写 @Mapper 注解,你可以使用 @MapperScan 注解在配置类上,一次性扫描多个 Mapper 接口:

import org.mybatis.spring.annotation.MapperScan;  
import org.springframework.context.annotation.Configuration;  
  
@Configuration  
@MapperScan("com.example.demo.mapper") // 指定Mapper接口所在的包路径  
public class MyBatisConfig {  
    // 其他配置...  
}

在上面的例子中,@MapperScan 注解用于指定 MyBatis 应该扫描哪个包下的 Mapper 接口。这样,在该包下的所有接口都会被自动注册为 MyBatis 的 Mapper 接口,而无需在每个接口上都添加 @Mapper 注解。

需要注意的是,虽然 @Mapper 注解本身提供了足够的功能来标识 Mapper 接口,但使用 @MapperScan 通常更加方便,因为它允许你一次性配置多个 Mapper 接口,减少了代码的重复。

Spring Cloud Alibaba的示例项目 integrated-account 中代码:

import org.springframework.stereotype.Repository;

/**
 * @author TrevorLink
 */
@Mapper
@Repository
public interface AccountMapper {

	@Select("SELECT money FROM account WHERE user_id = #{userId}")
	Integer getBalance(@Param("userId") String userId);

	@Update("UPDATE account SET money = money - #{price},update_time = #{updateTime} WHERE user_id = #{userId} AND money >= ${price}")
	int reduceBalance(@Param("userId") String userId, @Param("price") Integer price,
			@Param("updateTime") Timestamp updateTime);

}

服务层调用代码:

@Service
public class AccountServiceImpl implements AccountService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AccountMapper accountMapper;

	@Override
	@Transactional
	public void reduceBalance(String userId, Integer price) throws BusinessException {
		logger.info("[reduceBalance] currenet XID: {}", RootContext.getXID());

		checkBalance(userId, price);

		Timestamp updateTime = new Timestamp(System.currentTimeMillis());
		int updateCount = accountMapper.reduceBalance(userId, price, updateTime);
		if (updateCount == 0) {
			throw new BusinessException("reduce balance failed");
		}
	}

	@Override
	public Result<?> getRemainAccount(String userId) {
		Integer balance = accountMapper.getBalance(userId);
		if (balance == null) {
			return Result.failed("wrong userId,please check the userId");
		}
		return Result.success(balance);
	}

	private void checkBalance(String userId, Integer price) throws BusinessException {
		Integer balance = accountMapper.getBalance(userId);
		if (balance < price) {
			throw new BusinessException("no enough balance");
		}
	}

}

上面代码中,自动注入 AccountMapper 对象,然后用其执行了 sql 语句,实现账户余额查询和扣减的功能。

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
要创建一个Spring Boot MyBatisSQL Server代码下载,你可以按照以下步骤进行操作: 1. 首先,确保你已经安装了Java开发工具和Maven构建工具。 2. 创建一个新的Spring Boot项目。你可以通过使用Spring Initializr来快速搭建一个基本的Spring Boot项目结构。在Spring Initializr的网站上选择你需要的项目配置,包括项目的名称、包名、Java版本等。点击生成项目按钮,然后下载生成的zip包。 3. 解压下载的zip包,在你选择的目录下打开命令行或终端窗口。 4. 进入解压后的项目目录,运行以下Maven命令来导入项目依赖: ``` mvn clean install ``` 5. 接下来,你需要在项目的pom.xml文件中添加MyBatisSQL Server的依赖。例如,你可以添加以下依赖: ``` <dependencies> ... <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>8.4.1.jre11</version> </dependency> ... </dependencies> ``` 6. 在项目的配置文件(例如application.properties或application.yml)中添加SQL Server的连接信息,包括数据库URL、用户名和密码。例如,你可以添加以下配置: ``` spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=mydatabase spring.datasource.username=yourusername spring.datasource.password=yourpassword ``` 7. 创建一个MyBatisMapper接口和对应的映射文件,用于定义和执行SQL查询语句。你可以在Mapper接口中声明SQL查询方法,并且在映射文件中编写对应的SQL语句。 8. 在你的应用程序中使用自动注入注解(例如@Autowired)将Mapper接口注入到你的服务类或控制器类中。然后,你就可以在这些类中使用Mapper接口定义的方法来执行SQL查询了。 9. 最后,你可以启动你的Spring Boot应用程序,通过访问定义的接口来执行SQL查询操作。你可以使用Postman等工具来测试接口的响应结果。 希望以上步骤能够帮助你成功创建Spring Boot MyBatisSQL Server代码,并实现相关的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

因上精进,果上随缘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值