您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Spring Data Jpa原生SQL返回自定義對(duì)象最簡(jiǎn)潔方式是什么”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
此文章只討論兩種方式查詢, 使用jpa關(guān)鍵字查詢和自定義sql
// 方式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);
即通過定義一個(gè)接口接口 UserName,兩種方式都支持通過定義接口接受返回,JPA原生支持
public interface UserName { String getNname(); }
方式一 JAP原生支持自定義對(duì)象,但條件是而且只有一個(gè)構(gòu)造函數(shù),有些工具類需要用到默認(rèn)構(gòu)造函數(shù),不方便
方式二 JAP不支持自定義對(duì)象,會(huì)返回Object[] 對(duì)象數(shù)組
例子只是解決方式二, 如果需要解決方式一構(gòu)造函數(shù)問題,可以借鑒,下面例子自己實(shí)現(xiàn) 我們定義一個(gè)接口ReabamDTO
public interface ReabamDTO { }
內(nèi)容是map 轉(zhuǎn) 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可以返回自定義對(duì)象 */ @Test void t2() { List<UserName> a = usersRepository.findByName("A"); System.out.println(a); } /** * 自定義sql 自定義對(duì)象 */ @Test void t3() { List<UserName> a = usersRepository.findByName2("A"); System.out.println(a); } }
查看報(bào)錯(cuò)信息,找不到轉(zhuǎn)換器異常, 那么只需要加入對(duì)應(yīng)的裝換器就可以了,
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)
通過查看源碼, 獲取轉(zhuǎn)換器的位置 org.springframework.core.convert.support.GenericConversionService#getConverter
@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; }
繼續(xù)看源碼, 查找能加入轉(zhuǎn)換器位置 converter = this.converters.find(sourceType, targetType);
@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; }
此方法 源對(duì)象TupBackedMap父類或接口和UserName父類或接口進(jìn)行組合,獲取到對(duì)應(yīng)的轉(zhuǎn)換器
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中加入轉(zhuǎn)換器
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) { } }
查看調(diào)用 add 方法位置, org.springframework.core.convert.support.GenericConversionService#addConverter(org.springframework.core.convert.converter.GenericConverter) 最終定位到這里
“Spring Data Jpa原生SQL返回自定義對(duì)象最簡(jiǎn)潔方式是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。