Spring Data Jpa 原生SQL返回自定義對象最簡潔方式

Spring Data Jpa 原生SQL返回自定義對象最簡潔方式

此文章只討論兩種方式查詢, 使用jpa關鍵字查詢和自定義sqljava

// 方式1	
  1. List<UserName> findByName(String name);
  // 方式2
  2. @Query(value = "select name from t_users where name = ?", nativeQuery = true)
   List<UserName> findByName2(String name);
使用接口接收

即經過定義一個接口接口 UserName,兩種方式都支持經過定義接口接受返回,JPA原生支持spring

public interface UserName {
   String getNname();
}
自定義對象接收

方式一 JAP原生支持自定義對象,但條件是並且只有一個構造函數,有些工具類須要用到默認構造函數,不方便sql

方式二 JAP不支持自定義對象,會返回Object[] 對象數組數組

解決方案

例子只是解決方式二, 若是須要解決方式一構造函數問題,能夠借鑑,下面例子本身實現 咱們定義一個接口ReabamDTOide

public interface ReabamDTO {
}
GenericConverter實現類

內容是map 轉 ReabamDTO函數

public final class JpaConvert implements GenericConverter {

   @Override
   public Set<ConvertiblePair> getConvertibleTypes() {
      return Collections.singleton(new ConvertiblePair(Map.class, ReabamDTO.class));
   }

   @Override
   public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
      return map2Pojo(source, targetType.getObjectType());
   }

   public static <T> T map2Pojo(Object entity, Class<T> tClass) {
      CopyOptions copyOptions = CopyOptions.create()
            .setIgnoreCase(true)
            .setIgnoreError(true)
            .setIgnoreNullValue(true)
            .setFieldNameEditor(StrUtil::toUnderlineCase);
      return BeanUtil.toBean(entity, tClass, copyOptions);
   }
}

將自定義convert加入到GenericConversionService工具

@Configuration
public class JpaConfig {

   @PostConstruct
   public void init() {
      GenericConversionService genericConversionService = ((GenericConversionService) DefaultConversionService.getSharedInstance());
      genericConversionService.addConverter(new JpaConvert());
   }
}
測試
public interface UsersRepository extends JpaRepository<Users, Integer> {
   
    List<UserName> findByName(String name);
    
   @Query(value = "select name from t_users where name = ?", nativeQuery = true)
   List<UserName> findByName2(String name);
}
@Data
@ToString
@NoArgsConstructor
public class UserName implements ReabamDTO {
   private String name;
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class, properties = {"spring.profiles.active=local"})
class DemoApplicationTests {

   @Autowired
   private UsersRepository usersRepository;

   @Test
   void contextLoads() {
      Users users = new Users();
      users.setName("A");
      users.setAge(1);
      users.setAddress("AA");
      usersRepository.save(users);
   }

   /**
    * 非自定義sql能夠返回自定義對象
    */
   @Test
   void t2() {
      List<UserName> a = usersRepository.findByName("A");
      System.out.println(a);
   }

   /**
    * 自定義sql 自定義對象
    */
   @Test
   void t3() {
      List<UserName> a = usersRepository.findByName2("A");
      System.out.println(a);
   }
}

原理可選擇觀看

查看報錯信息,找不到轉換器異常, 那麼只須要加入對應的裝換器就能夠了,測試

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.architeture.demo.UserName]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:322)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175)
at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:309)
at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:225)
at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:236)
at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:156)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:158)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143)

經過查看源碼, 獲取轉換器的位置 org.springframework.core.convert.support.GenericConversionService#getConverterthis

@Nullable
protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
   ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
   GenericConverter converter = this.converterCache.get(key);
   if (converter != null) {
      return (converter != NO_MATCH ? converter : null);
   }

   converter = this.converters.find(sourceType, targetType);
   if (converter == null) {
      converter = getDefaultConverter(sourceType, targetType);
   }

   if (converter != null) {
      this.converterCache.put(key, converter);
      return converter;
   }

   this.converterCache.put(key, NO_MATCH);
   return null;
}

繼續看源碼, 查找能加入轉換器位置 converter = this.converters.find(sourceType, targetType);code

@Nullable
public GenericConverter find(TypeDescriptor sourceType, TypeDescriptor targetType) {
   // Search the full type hierarchy
   // 獲取 
   List<Class<?>> sourceCandidates = getClassHierarchy(sourceType.getType());
   List<Class<?>> targetCandidates = getClassHierarchy(targetType.getType());
   for (Class<?> sourceCandidate : sourceCandidates) {
      for (Class<?> targetCandidate : targetCandidates) {
         ConvertiblePair convertiblePair = new ConvertiblePair(sourceCandidate, targetCandidate);
         GenericConverter converter = getRegisteredConverter(sourceType, targetType, convertiblePair);
         if (converter != null) {
            return converter;
         }
      }
   }
   return null;
}

此方法 源對象TupBackedMap父類或接口和UserName父類或接口進行組合,獲取到對應的轉換器

TupBackedMap的父類或接口

org.springframework.core.convert.support.GenericConversionService#addConverter(org.springframework.core.convert.converter.GenericConverter)

@Nullable
private GenericConverter getRegisteredConverter(TypeDescriptor sourceType,
      TypeDescriptor targetType, ConvertiblePair convertiblePair) {

   // Check specifically registered converters
   ConvertersForPair convertersForPair = this.converters.get(convertiblePair);
   if (convertersForPair != null) {
      GenericConverter converter = convertersForPair.getConverter(sourceType, targetType);
      if (converter != null) {
         return converter;
      }
   }
   // Check ConditionalConverters for a dynamic match
   for (GenericConverter globalConverter : this.globalConverters) {
      if (((ConditionalConverter) globalConverter).matches(sourceType, targetType)) {
         return globalConverter;
      }
   }
   return null;
}

能夠看到在 ConvertersForPair convertersForPair = this.converters.get(convertiblePair); 在convertes中加入轉換器

org.springframework.core.convert.support.GenericConversionService.Converters

private static class Converters {

   private final Map<ConvertiblePair, ConvertersForPair> converters = new LinkedHashMap<>(36);

   public void add(GenericConverter converter) {
   }
}

查看調用 add 方法位置, org.springframework.core.convert.support.GenericConversionService#addConverter(org.springframework.core.convert.converter.GenericConverter) 最終定位到這裏

相關文章
相關標籤/搜索