【问题标题】:Id to Entity conversion is not working in Spring Boot 2.2.8 and higherId 到实体的转换在 Spring Boot 2.2.8 及更高版本中不起作用
【发布时间】:2020-07-21 21:49:59
【问题描述】:

我尝试为我的应用程序升级 Spring Boot 版本,发现行为有所不同。从 2.2.7 切换到 2.2.8(及更高版本)时,从标识符到数据库实体的转换停止工作。

应用:

@SpringBootApplication
public class DomainClassConverterTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(DomainClassConverterTestApplication.class, args);
    }

    @Bean
    CommandLineRunner initialize(ModelRepository modelRepository) {
        return args -> {
            Stream.of("Model 1", "Model 2", "Model X").forEach(name -> {
                Model model = new Model();
                model.setName(name);
                modelRepository.save(model);
            });
        };
    }
}

控制器:

@RestController
public class ModelController {
    private final ModelRepository repository;

    public ModelController(ModelRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/models/{id}")
    public Model getModel(@PathVariable("id") Model model) {
        return model;
    }

    @GetMapping("/models")
    public Page<Model> findAllModels(Pageable pageable) {
        return repository.findAll(pageable);
    }
}

型号:

@Entity
public class Model {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;

    public Model() {}

    public long getId() { return id; }

    public void setId(long id) { this.id = id; }

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    @Override
    public String toString() { return "Model{id=" + id + ", name='" + name + "'}"; }
}

在调查了这个问题后,我发现这个问题的根本原因是在DomainClassConverter类中。我知道问题出在setApplicationContext 方法上。该方法使用延迟初始化,并将转换器添加到СonversionService,但仅在第一次使用之后。但是这个事件永远不会发生,因为转换器没有在СonversionService 中注册。方法如下:

public void setApplicationContext(ApplicationContext context) {

    this.repositories = Lazy.of(() -> {

        Repositories repositories = new Repositories(context);

        this.toEntityConverter = Optional.of(new ToEntityConverter(repositories, conversionService));
        this.toEntityConverter.ifPresent(it -> conversionService.addConverter(it));

        this.toIdConverter = Optional.of(new ToIdConverter(repositories, conversionService));
        this.toIdConverter.ifPresent(it -> conversionService.addConverter(it));

        return repositories;
    });
}

【问题讨论】:

    标签: spring-boot spring-mvc spring-data-jpa


    【解决方案1】:

    这是一个错误DATACMNS-1743,已在 2.2.8、2.3.2 和更高版本中修复。

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 2017-04-28
      • 1970-01-01
      • 2020-03-30
      • 2013-05-18
      • 2014-05-07
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多