ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
**1. 两个实体类** ```java @Data public class Book { private Integer bookId; } @Data public class BookDto { private Integer bookDtoId; } ``` **2. 异常处理** ```java public class Validator { /** * 该方法只有一个参数 */ public Integer validateId(Integer id) throws ValidationException { if(id == -1){ throw new ValidationException("Invalid value in ID"); } return id; } } ``` **3. 映射接口** ```java /** * 使用uses引入Validator */ @Mapper(uses = {Validator.class}) public interface BookMapper { BookMapper INSTANCE = Mappers.getMapper(BookMapper.class); /** * 当source.bookId的类型与方法validateId(Integer id)的参数类型一致时(必须一致,子类或者基本类对包装类都不可以), * 就会调用方法validateId(Integer id)。 * @throws ValidationException throws可有可无 */ @Mapping(source = "source.bookId", target = "bookDtoId") BookDto toDto(Book source) throws ValidationException; } ``` **4. 测试** ```java @Test public void testBookMapper() throws ValidationException { Book book = new Book(); book.setBookId(-1); //抛出异常javax.xml.bind.ValidationException: Invalid value in ID BookDto bookDto = BookMapper.INSTANCE.toDto(book); System.out.println("Book:" + book); System.out.println("BookDto:" + bookDto); } ```