java - Spring Data REST + Hibernate 5 + Jackson LAZY 序列化失败

标签 java spring hibernate jackson spring-data-rest

我有 2 个实体:用户和地址。 设置关系如下:

地址

@Entity
@Table(name = "addresses")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Address {
    private static final long serialVersionUID = 1L;
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "username")
    private User user;

用户

@Entity
@Table(name = "users")
public class User {
    @Id
    private String username;

    (...)

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<Address> addresses;

每当我打电话 GET http://localhost:8080/api/data/users/{USERNAME}/addresses对于具有一个或多个地址实体的用户的用户名,结果为:

状态 500

{
    "cause": null,
    "message": "Id must be assignable to Serializable!: to.wysylam.couriersystem.api.entities.User"
}

还值得一提的是,即使 Spring Data REST 生成链接:

"_links": {
  "self": {
    "href": "http://localhost:8080/api/data/addresses/33"
  },
  "address": {
    "href": "http://localhost:8080/api/data/addresses/33"
  },
  "user": [
    {
      "href": "http://localhost:8080/api/data/users"
    },
    {
      "href": "http://localhost:8080/api/data/addresses/33/user"
    }
  ]
}

http://localhost:8080/api/data/addresses/33/user链接根本不起作用。 (抛出java.lang.NoClassDefFoundError:javax/servlet/jsp/jSTL/core/Config)

到目前为止,我尝试将 Address 实体中的 LAZY 更改为 EAGER FetchingType,然后行为更改如下:

  • 我不能GET http://localhost:8080/api/data/addresses (错误消息为 500,其中包含“Id 必须可分配给可序列化!:to.wysylam.couriersystem.api.entities.User”)

  • 我可以GET http://localhost:8080/api/data/users/{USERNAME}/addresses

老实说,我现在没有主意。

配置文件定义如下:

@Configuration
@ComponentScan(basePackages = { "to.wysylam.couriersystem.api.controllers",
                            "to.wysylam.couriersystem.api.services",
                            "to.wysylam.couriersystem.api.hateoas"
                            })
@Import({JpaConfig.class,
    SecurityConfig.class,
    DataRestConfig.class,
    RepositoryRestMvcConfiguration.class
})
public class AppConfig {

}

@Configuration
public class DataRestConfig extends RepositoryRestConfigurerAdapter {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config){
    config.setRepositoryDetectionStrategy(
                 RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED
    );
    config.exposeIdsFor(User.class);
    config.setBasePath("/data");
}

@Bean
protected Module module(){
    return new Hibernate5Module();
}

@Override
public void configureConversionService(ConfigurableConversionService configurableConversionService){
    configurableConversionService.addConverter(String.class, String[].class, stringToStringArrayConverter());
}

private Converter<String, String[]> stringToStringArrayConverter(){
    return (source) -> StringUtils.delimitedListToStringArray(source, ";");

}
}

@Configuration
@EnableJpaRepositories(basePackages =   "to.wysylam.couriersystem.api.repositories")
public class JpaConfig {
private static Properties getJpaProperties(){
    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", "validate");
    jpaProperties.put("hibernate.default_schema", "couriersystem");
    jpaProperties.put("hibernate.dialect",  "org.hibernate.dialect.PostgreSQL82Dialect");
    jpaProperties.put("hibernate.enable_lazy_load_no_trans","true");
    return jpaProperties;
}

@Bean
public static LocalContainerEntityManagerFactoryBean entityManagerFactory(){
    LocalContainerEntityManagerFactoryBean asBean = new LocalContainerEntityManagerFactoryBean();
    asBean.setDataSource(dataSource());
    asBean.setPackagesToScan("to.wysylam.couriersystem.api.entities");
    asBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    asBean.setJpaProperties(getJpaProperties());

    return asBean;
}

@Bean(name = "dataSource")
public static DriverManagerDataSource dataSource(){
    DriverManagerDataSource bean = new DriverManagerDataSource();
    bean.setDriverClassName("org.postgresql.Driver");
    bean.setUrl("jdbc:postgresql://localhost:5432/postgres");
    bean.setUsername("dev");
    bean.setPassword("pwd");
    return bean;
}

@Bean
public static JpaTransactionManager transactionManager(){
    JpaTransactionManager asBean = new JpaTransactionManager();
    asBean.setEntityManagerFactory(entityManagerFactory().getObject());
    return asBean;
}

@Bean
public static PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
    return new PersistenceExceptionTranslationPostProcessor();
}

@Bean
public static HibernateExceptionTranslator hibernateExceptionTranslator(){
    return new HibernateExceptionTranslator();
}
}

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "to.wysylam.couriersystem.api.controllers")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import(AppConfig.class)
public class WebConfig implements WebMvcConfigurer {

@Bean
public InternalResourceViewResolver viewResolver(){
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

@Override
public void addFormatters(FormatterRegistry registry){
    registry.removeConvertible(String.class, String[].class);
    registry.addConverter(String.class, String[].class, stringToStringArrayConverter());
}

private Converter<String, String[]> stringToStringArrayConverter(){
    return (source) -> StringUtils.delimitedListToStringArray(source, ";");
}
}

感谢任何帮助

更新

期间,我尝试将 User 类的 ID 从 String 更改为 Long。 然而,问题仍然存在。显然......

更新2

一些有趣的日志转储(处理 GET <host>/api/data/addresses 时):

[DEBUG] 2017-11-06 18:25:01.053 [http-nio-8080-exec-39] ExceptionHandlerExceptionResolver - Resolving exception from handler [public org.springframework.hateoas.Resources<?> org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException]: java.lang.IllegalArgumentException: Id must be assignable to Serializable!: to.wysylam.couriersystem.api.entities.User

[DEBUG] 2017-11-06 18:25:01.055 [http-nio-8080-exec-39] ExceptionHandlerExceptionResolver - Resolving exception from handler [public org.springframework.hateoas.Resources<?> org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException]: java.lang.IllegalArgumentException: Id must be assignable to Serializable!: to.wysylam.couriersystem.api.entities.User

最佳答案

在多对一类上设置@JsonSerialize(as = Address.class)对我的情况有帮助......

关于java - Spring Data REST + Hibernate 5 + Jackson LAZY 序列化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113242/

相关文章:

java - 什么是 NLP 中经过训练的模型?

java - 使用 sql 查询在 hibernate 中创建一个新的对象实例

java - Spring错误处理不起作用

java - 从 jboss fusion 控制台中删除了 Fabric

java - Spring 是否要求所有 bean 都具有默认构造函数?

java - Spring Boot 自定义身份验证提供程序登录后重定向不起作用

java - hibernate 映射 : OneToMany and OneToOne on child object property

java - Hibernate 不允许按顺序递增 5

java - Oracle Hibernate 时间戳/日期映射问题

java - 如何使用 QuickBooks Online Java SDK 创建发票实体