Skip to content

业务与持久层(业务逻辑、数据库操作)

分层开发的核心,负责封装业务逻辑、处理数据库操作,保证数据一致性(事务),是项目的“业务核心”。

注解 作用说明
@Service 标记当前类为业务逻辑层组件,让 Spring 管理,便于依赖注入
@Mapper MyBatis 专用注解,标记数据访问层接口,MyBatis 会自动生成接口的代理实现类,无需手动编写实现
@Repository 标记数据访问层组件(多用于 JPA 或传统 JDBC),与 @Mapper 功能类似,侧重非 MyBatis 场景
@Transactional 声明式事务管理,标记在方法或类上,保证方法内的数据库操作原子性(要么全成、要么全败)
// 1. 持久层(MyBatis,@Mapper)
@Mapper // 标记为 MyBatis 数据访问接口,自动生成代理实现
public interface UserMapper {
    // MyBatis 注解式 SQL,查询用户
    @Select("select id, username, age from user where id = #{id}")
    User selectById(Long id);

    // 新增用户,配合事务使用
    @Insert("insert into user(username, age) values(#{username}, #{age})")
    int insert(User user);
}

// 2. 业务层(@Service + @Transactional)
@Service // 标记为业务层组件,被 Spring 管理
public class UserServiceImpl {

    // 注入持久层 Mapper(依赖注入,后续会讲)
    @Autowired
    private UserMapper userMapper;

    // 声明事务:保证查询+新增的原子性(实际场景可根据需求调整)
    @Transactional
    public User addAndGet(User user) {
        // 1. 新增用户
        userMapper.insert(user);
        // 2. 查询新增后的用户(模拟业务逻辑)
        return userMapper.selectById(user.getId());
    }

    // 无事务的查询方法
    public User getById(Long id) {
        return userMapper.selectById(id);
    }
}

// 3. 控制层(调用业务层,整合前面的 Web 注解)
@RestController
@RequestMapping("/user")
public class UserController {

    // 注入业务层 Service
    @Autowired
    private UserServiceImpl userService;

    // 调用业务层方法,返回结果
    @PostMapping("/addAndGet")
    public User addAndGet(@RequestBody User user) {
        return userService.addAndGet(user);
    }

    @GetMapping("/get/{id}")
    public User getById(@PathVariable Long id) {
        return userService.getById(id);
    }
}