Springboot,hibernate4和hsql访问架构不正确?

时间:2016-04-20 14:04:47

标签: java hibernate spring-boot hsqldb

我试图一起使用springboot,hsql和hibernate来持久化并检索一些相当无聊的数据。我遇到的问题是hibernate似乎无法正确引用我的表,抛出以下异常:

ERROR [main] (SpringApplication.java:826) - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'strangerEntityManagerFactory' defined in class path resource [com/healz/stranger/config/profiles/GenericSqlConfig.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Missing column: user_USER_ID in PUBLIC.STRANGER.PROTECTED_PROPERTIES
at
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
...

最初我使用的是HSQL的默认模式名PUBLIC,并注意到抛出的异常是应用程序无法找到PUBLIC.PUBLIC.PROTECTED_PROPERTIES。这看起来非常可疑 - 为什么会有一个"额外的层" PUBLIC在这里?它绝对不是正确的。执行EntityManagerFactory设置的代码如下所示:

@Log4j
@Configuration
@EnableAspectJAutoProxy
@ComponentScan (basePackages = {"com.healz.stranger.data"})
@EnableJpaRepositories (
  entityManagerFactoryRef="strangerEntityManagerFactory",
  transactionManagerRef="txManager",
  basePackages={"com.healz.stranger.data.model"}
)
@EntityScan (basePackages={
    "com.healz.stranger.data.model" 
    })
@Import ( {HsqlConfig.class, DevMySqlConfig.class, ProdMySqlConfig.class} )
public class GenericSqlConfig {

  @Configuration
  @EnableTransactionManagement(order = Ordered.HIGHEST_PRECEDENCE)
  @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  protected static class TransactionManagementConfigurer {
    // ignore annoying bean auto-proxy failure messages
  }

  @Bean
  public static PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() throws Exception {
    return new PersistenceAnnotationBeanPostProcessor();
  }

  @Bean
  public JpaDialect jpaDialect() {
    return new HibernateJpaDialect();
  }

  @Autowired
  @Qualifier("hibernateProperties") 
  private Properties hibernateProperties;

  @Autowired
  @Qualifier("dataSource") 
  private DataSource dataSource;


  @Bean (name="strangerEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean strangerEntityManagerFactory(
                final @Qualifier("hibernateProperties") Properties props,
                final JpaDialect jpaDialect) {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setPackagesToScan("com.healz.stranger.data");

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    emf.setJpaVendorAdapter(vendorAdapter);
    emf.setJpaProperties(hibernateProperties);
    emf.setJpaDialect(jpaDialect);

    emf.setPersistenceUnitName("strangerEntityManagerFactory");

    return emf;
  }

  @Bean (name="sessionFactory")
  public SessionFactory configureSessionFactory(LocalContainerEntityManagerFactoryBean emf) {
    SessionFactory sessionFactory = emf.getObject().unwrap(SessionFactory.class);
    return sessionFactory;
  }

  /**
   * Helper method to get properties from a path. 
   * @param path
   * @return
   */
  @SneakyThrows (IOException.class)
  public static Properties getHibernatePropertiesList(final String path) {
    Properties props = new Properties();
    Resource resource = new ClassPathResource(path); 
    InputStream is = resource.getInputStream();
    props.load( is );
    return props;
  }

  @Bean (name="txManager")
  @Autowired
  public PlatformTransactionManager getTransactionManager(LocalContainerEntityManagerFactoryBean lcemfb, JpaDialect jpaDialect) {
    EntityManagerFactory emf = null;
    emf = lcemfb.getObject();

    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(emf);
    jpaTransactionManager.setJpaDialect(jpaDialect);
    return jpaTransactionManager;
  }
}

HSQL配置如下所示:

@Configuration
@Profile ("hsql")
public class HsqlConfig {
  @Bean(name = "dataSource")
  public DataSource initDataSource() {
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
                                        .setType(EmbeddedDatabaseType.HSQL)
                                        .addScript("classpath:env/dbcache/hsql-schema.sql")
                                        .addScript("classpath:env/dbcache/hsql-data.sql");
    builder.setName("stranger");
    builder.setScriptEncoding("UTF-8");
    return builder.build();
  }

  @Bean(name = "hibernateProperties")
  public Properties getHibernateProperties() {
    Properties props = new Properties();
    props.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    props.put("hibernate.hbm2ddl.auto", "validate"); // using auto and ignoring the hsql scripts "works", but isn't correct
    props.put("hibernate.default_schema", "stranger");
    props.put("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");
    return props;
  }

}

另一个奇怪的事情是,hibernate似乎正在寻找一个名为user_USER_ID而不是USER_ID的列,而且我不确定为什么会发生这种情况。我怀疑这一切都是由映射错误引起的,因为类似的代码似乎与不同配置的EntityMappingFactory一起工作,但我不想排除这种可能性。其代码如下:

@Entity (name="properties")
@Table (name="PROTECTED_PROPERTIES")
public class DbProtectedProperties extends AbstractModel<DbProtectedPropertiesId> implements Serializable {

  private static final long serialVersionUID = 1L;

  public void setId(DbProtectedPropertiesId id) {
    super.id = id;
  }

  @EmbeddedId
  public DbProtectedPropertiesId getId() {
    if (super.id == null) {
      super.id = new DbProtectedPropertiesId();
    }
    return super.id;
  }

  @Column (name="PROPERTY_VALUE", length=4096, nullable=false)
  public String getPropertyValue() {
    return propertyValue;
  }


  @Setter
  private String propertyValue;

}

ID类:

@EqualsAndHashCode ( of={ "user", "propertyName" } )
@ToString
public class DbProtectedPropertiesId implements Serializable {

  private static final long serialVersionUID = 1L;

  @Setter
  private DbUsers user;

  @Setter
  private String propertyName;

  @ManyToOne (optional=false, fetch=FetchType.EAGER)
  @PrimaryKeyJoinColumn (name="USER_ID")
  public DbUsers getUser() {
    return user;
  }

  @Column (name="PROPERTY_NAME", length=2048, nullable=false, insertable=false, updatable=false)
  public String getPropertyName() {
    return propertyName;
  }
}

2 个答案:

答案 0 :(得分:0)

这里的问题似乎是Spring Boot定义了自己的beforeEach inject实例,第二个定义导致了奇怪的冲突。此外,没有理由将JPA方言应用于LocalContainerEntityManagerFactoryBean,因为TransactionManager将从TransactionManager中获取设置,Spring Boot无论如何都会对其进行配置。

答案 1 :(得分:0)

我假设您在StrangerApplication包中有一个com.healz.stranger,如果您没有真正应该或在那里移动它,因为它可以为您节省大量配置。

您正在使用Spring Boot,但您的配置非常努力。

首先是应用程序

@SpringBootApplication
public class StrangerApplication {

    public static void main(String... args) throws Exception {
        SpringApplication.run(StrangerApplication.class, args);
    }

    @Bean (name="sessionFactory")
    public SessionFactory configureSessionFactory(EntityManagerFactoryBean emf) {
        SessionFactory sessionFactory = emf.unwrap(SessionFactory.class);
        return sessionFactory;
    }

}

现在创建一个application.properties,其中包含默认属性和常规属性。对于hsql个人资料,添加application-hsql.properties,其中至少包含以下内容(从您的配置类中扣除)。

spring.jpa.properties.hibernate.default_schema=stranger
spring.jpa.hibernate.ddl-auto=validate # maybe this needs to be in application.properties (?)

然后将您的hsql-data.sqlhsql-schema.sql重命名为data-gsql.sqlschema-hsql.sql,并将其放置在src/main/resources春季启动时将检测特定配置文件的那些(解释{参考指南中的{3}}。确保在schema.sql中的新架构中创建架构和表格。

其他所有内容都将自动配置(Spring Data JPA,AspectJ代理,实体检测)。您基本上可以删除所有配置类,并为剩余的2个MySQL配置选项创建添加application-{profile}.properties

一般的建议是使用框架而不是试图解决它。