@Repository 和@Mapper 有什么区别,应该分别怎么使用?

董俊杰 / 2024-07-19 / 原文

@Repository@Mapper 都是用于标识DAO(Data Access Object)类的注解,但它们的用途和功能有所不同。以下是它们的详细区别和使用方法:

@Repository

@Repository 是Spring框架提供的注解,主要用于标识数据访问层(DAO)类。

特点

  1. Spring组件

    • @Repository 是一个Spring组件注解,表示该类是一个Spring管理的bean。
    • 可以与Spring的@ComponentScan一起使用,自动扫描和检测这些类。
  2. 异常转换

    • Spring会自动捕获数据访问层(DAO)抛出的异常,并将它们转换为Spring的DataAccessException。这有助于在不同的持久化技术之间提供一致的异常处理。

使用示例

假设有一个UserRepository接口及其实现类:

import org.springframework.stereotype.Repository;

@Repository
public class UserRepositoryImpl implements UserRepository {
    // 数据访问方法的实现
}

在配置文件或启动类中启用组件扫描:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example.project")
public class AppConfig {
}

@Mapper

@Mapper 是MyBatis框架提供的注解,用于标识MyBatis的Mapper接口。

特点

  1. MyBatis组件

    • @Mapper 是一个MyBatis注解,用于标识一个Mapper接口。MyBatis会自动为这些接口生成代理对象,用于执行SQL操作。
  2. SQL映射

    • @Mapper 通常与MyBatis的XML映射文件或注解一起使用,定义SQL查询和映射结果。
  3. 与Spring的整合

    • 使用MyBatis-Spring集成时,@Mapper可以与@MapperScan一起使用,自动扫描和注册Mapper接口。

使用示例

假设有一个UserMapper接口及其XML映射文件:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User findUserById(int id);
}

在配置文件或启动类中启用Mapper扫描:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.example.project.mapper")
public class MyBatisConfig {
}

选择使用 @Repository 还是 @Mapper

  • 使用 @Repository

    • 如果你在使用Spring Data JPA或其他Spring支持的持久化框架,@Repository是一个很好的选择。
    • 当你需要Spring的异常转换功能时,使用@Repository
  • 使用 @Mapper

    • 如果你在使用MyBatis作为持久化框架,@Mapper是必需的。
    • 当你需要使用MyBatis的动态SQL、SQL映射文件或MyBatis特定功能时,使用@Mapper

例子总结

假设你有一个简单的用户数据访问需求,分别使用Spring Data JPA和MyBatis来实现。

使用Spring Data JPA:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}

使用MyBatis:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User findUserById(int id);
}

在配置文件或启动类中启用相应的扫描:

// Spring Data JPA
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example.project")
public class AppConfig {
}

// MyBatis
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.example.project.mapper")
public class MyBatisConfig {
}

总之,@Repository@Mapper 各自适用于不同的持久化框架。根据具体的持久化需求和框架选择合适的注解,以充分利用Spring和MyBatis的功能。