【问题标题】:@Converter annotated class not getting auto detected in spring-boot project@Converter 带注释的类未在 spring-boot 项目中自动检测到
【发布时间】:2015-05-30 16:50:33
【问题描述】:

我正在使用带有 hibernate.version:4.3.6.Final 的 spring-boot 1.2.2 进行简单操作,并使用 @Converter 将 java8 LocalDateTime 字段映射到时间戳。

在我的转换器类中,我使用了 autoApply=true,如下所示。

@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements
    AttributeConverter {
    @Override
    public java.sql.Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
        return Timestamp.valueOf(entityValue);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(java.sql.Timestamp databaseValue) {
        return databaseValue.toLocalDateTime();
    }
}

但是,我仍然必须在我的实体上使用 @Convert。 转换器类是我扫描的包的一部分。 在不对所有数据库条目使用 @Convert 的情况下,我必须做些什么才能让它自动工作吗?

::另外::

这是我的数据库配置

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    lef.setDataSource(dataSource());
    lef.setJpaVendorAdapter(jpaVendorAdapter());
    lef.setPackagesToScan("path to domain and Converter class");
    lef.afterPropertiesSet();
    return lef;
}

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

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.ORACLE);
    adapter.setShowSql(false);
    adapter.setGenerateDdl(false);
    return adapter;
}

【问题讨论】:

  • @Converter 是什么? Spring 仅检测 @Component 注释 bean(或带有注释的 bean,该注释本身带有 @Component 注释,如 @Service。)。
  • 同意@M.Deinum,但我也在配置hibernate,并且已经定义了Hibernate要扫描的包。我还用我的 Database 和 Hibernate Config 类更新了这个问题。我猜,我遗漏了一些东西......我不确定它是什么?
  • 您使用的是 Spring Boot,为什么要手动配置所有内容。但是,如果不是@Component@Converter 又是什么,它什么也不做。 hibernate 也可能需要知道它而不是 spring。
  • 我同意,但我不知道如何让 hibernate 知道这个转换器。有没有办法告诉休眠将此转换器嵌入到它已经拥有的转换器列表中......?
  • 您可以使用@EntityScan 并为其提供要扫描Hibernate 的软件包列表。您可以包含 JPA 实体所在的包以及 Converter 的包。然后不再需要自定义配置(除非您需要它)。

标签: spring hibernate type-conversion spring-boot jpa-2.1


【解决方案1】:

顺序不对,应该是:

public class LocalDateTimePersistenceConverter implements 
  AttributeConverter<LocaleDateTime, java.sql.Timestamp>

正如 Javadoc 所述:

javax.persistence.AttributeConverter<X, Y>
Parameters:
  X the type of the entity attribute
  Y the type of the database column

【讨论】:

    【解决方案2】:

    我唯一能看到的是您可能需要更改下面的这一行

    public class LocalDateTimePersistenceConverter implements
    AttributeConverter<java.sql.Timestamp, LocaleDateTime>
    

    因此,Spring 会知道如何自动转换哪种类型的属性。

    【讨论】:

    • 谢谢...这确实是个错误。
    猜你喜欢
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多