Hibernate не генерирует JSON reponse By Native Query (преобразование Enum завершается неудачно) - PullRequest
0 голосов
/ 19 февраля 2020

У меня есть пользовательский ответ с типом enum. Я попытался возвратить собственный запрос (запрос сложен с подзапросами, поэтому мой выбор - это нативный запрос, а не hql), но есть проблема с enum. Я попробовал следующее:

public class ExampleRepositoryImpl implements ExampleRepositoryCustom {

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public SessionFactory getSessionFactory() {
        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        return entityManagerFactory.unwrap(SessionFactory.class);
    }

    @SuppressWarnings("deprecation")
    public List<MyResponse> findEntities(String query) {

        Properties params = new Properties();
        params.put("enumClass", MyEnum.class.getName()); //tried also params.put(EnumType.Enum, MyEnum.class.getName())
        params.put(EnumType.NAMED, true);

        //option 1
        /* 
        EnumType enumtype = new EnumType();
        enumtype.setParameterValues(params); //here it throws exception
        CustomType customType = new CustomType(enumtype);
        */

        //option 2 . It throws exception for TypeLocatorImpl(new TypeResolver...
        //Type customType = new TypeLocatorImpl(new TypeResolver(null, null)).custom(EnumType.class, params);

        //option 3. exception java.lang.NoSuchMethodException: com.path.MyEnum.<init>()
        Type customType = getSessionFactory().getTypeHelper().custom(MyEnum.class, params);


        return  (List<MyResponse>) em.createNativeQuery(query).unwrap(SQLQuery.class)
                .addScalar("customId", StandardBasicTypes.INTEGER)
                .addScalar("status", customType)
                .addScalar("customName", StringType.INSTANCE)
                .setResultTransformer(Transformers.aliasToBean(MyResponse.class)).getResultList();
    }

Есть идеи?

...