java如何添加mapper
在Java中添加Mapper的方法
使用MyBatis框架
在MyBatis中,Mapper通常指代数据库操作的接口或XML文件。以下是添加Mapper的步骤:
-
创建Mapper接口 定义一个Java接口,使用注解或XML文件描述SQL操作:
public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User getUserById(int id); } -
配置Mapper扫描 在MyBatis配置中声明Mapper接口的位置:
<!-- mybatis-config.xml --> <mappers> <mapper class="com.example.mapper.UserMapper"/> </mappers>或使用包扫描:
<mappers> <package name="com.example.mapper"/> </mappers> -
Spring集成配置 如果使用Spring Boot,在application.properties中添加:
mybatis.mapper-locations=classpath:mapper/*.xml
使用Spring Data JPA
-
创建Repository接口 继承JpaRepository接口:
public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); } -
启用JPA Repository扫描 在Spring Boot主类添加注解:
@SpringBootApplication @EnableJpaRepositories("com.example.repository") public class Application { ... }
手动实现Mapper模式
-
定义Mapper接口
public interface UserMapper { UserDTO toDto(User entity); User toEntity(UserDTO dto); } -
实现Mapper类
@Component public class UserMapperImpl implements UserMapper { @Override public UserDTO toDto(User entity) { // 转换逻辑 } @Override public User toEntity(UserDTO dto) { // 转换逻辑 } } -
使用Mapper 通过依赖注入使用:
@Autowired private UserMapper userMapper;
使用MapStruct自动生成Mapper
-
添加依赖
<dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.5.Final</version> </dependency> -
定义Mapper接口
@Mapper public interface UserMapper { UserMapper INSTANCE = Mappers.getMapper(UserMapper.class); UserDTO toDto(User entity); User toEntity(UserDTO dto); } -
编译时生成实现 MapStruct会在编译时自动生成实现类,无需手动编写转换逻辑。







