Spring Boot 水果表示例:FruitMapper 和 FruitService 代码
以下是一个示例的 Spring Boot 水果表的 FruitMapper 和 FruitService 层代码:
FruitMapper.java:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface FruitMapper {
@Select('SELECT * FROM fruits WHERE id = #{id}')
Fruit getFruitById(@Param('id') int id);
// 其他数据库操作方法...
}
FruitService.java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FruitService {
private final FruitMapper fruitMapper;
@Autowired
public FruitService(FruitMapper fruitMapper) {
this.fruitMapper = fruitMapper;
}
public Fruit getFruitById(int id) {
return fruitMapper.getFruitById(id);
}
// 其他业务逻辑方法...
}
在上述代码中,FruitMapper 使用了 MyBatis 的注解来定义数据库操作方法。@Mapper 注解将该接口声明为 MyBatis 的 Mapper 接口,@Select 注解用于定义查询语句。
FruitService 使用了 @Service 注解来声明该类为 Spring 的 Service 组件。构造函数使用 @Autowired 注解来自动注入 FruitMapper 实例。该类中的 getFruitById 方法调用了 FruitMapper 中的 getFruitById 方法来查询水果信息。
请根据实际需求进行适当的修改和扩展。
原文地址: https://www.cveoy.top/t/topic/mv37 著作权归作者所有。请勿转载和采集!