简体   繁体   English

如何在spring boot中注册jpa转换器?

[英]How to register jpa converter in spring boot?

I've an entity called Lawyer and the following piece of code in a LawyerRepository :我有一个名为Lawyer的实体和LawyerRepository的以下代码:

import javaslang.control.Option;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface LawyerRepository extends JpaRepository<Lawyer, Long> {

    @Query("select distinct l from Lawyer l where l.account.username = :email")
    Option<Lawyer> findLawyerByEmail(@Param("email") String email);

}

As you can see I'd like to return javaslang.control.Option instead of java.util.Optional .如您所见,我想返回javaslang.control.Option而不是java.util.Optional It results in the following exception:它导致以下异常:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.util.ArrayList] to type [javaslang.control.Option] for value '[lawyer.Lawyer@5e4c0db5]'; org.springframework.core.convert.ConversionFailedException:无法从类型 [java.util.ArrayList] 转换为类型 [javaslang.control.Option] 的值“[lawyer.Lawyer@5e4c0db5]”; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.ArrayList] to type [javaslang.control.Option]嵌套异常是 org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型 [java.util.ArrayList] 转换为类型 [javaslang.control.Option] 的转换器

And here's the converter:这是转换器:

import javaslang.control.Option;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class OptionConverter implements Converter<ArrayList<?>, Option<?>> {

    @Override
    public Option<?> convert(ArrayList<?> input) {
        if (true) {
            throw new RuntimeException("lol");
        }
        return null;
    }

}

My question is how to register the converter I provided properly?我的问题是如何正确注册我提供的转换器?

Seems Spring's converter(springframework.core.convert.converter.Converter) doesn't work with JPA.似乎 Spring 的转换器(springframework.core.convert.converter.Converter)不适用于 JPA。

U may have to use JPA Attribute Converter: http://www.thoughts-on-java.org/jpa-21-type-converter-better-way-to/ .您可能必须使用 JPA 属性转换器: http : //www.thoughts-on-java.org/jpa-21-type-converter-better-way-to/

It's good that Spring can make Spring's converter work with JPA, so it would be consistent as other spring-data-* projects. Spring 可以让 Spring 的转换器与 JPA 一起工作是很好的,所以它会和其他 spring-data-* 项目保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM