我有简单的spring- jpa配置,在其中配置了Hibernate的ImprovedNamingStrategy。这意味着,如果我的实体类具有一个变量userName,那么Hibernate应该将其转换为user_name用于查询数据库。但是,在我升级到Hibernate 5之后,这种命名转换就停止了。
ImprovedNamingStrategy
userName
user_name
错误:“字段列表”中的未知列“ user0_.userName”
这是我的Hibernate配置:
@Configuration @EnableJpaRepositories("com.springJpa.repository") @EnableTransactionManagement public class DataConfig { @Bean public DataSource dataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/test"); ds.setUsername("root"); ds.setPassword("admin"); return ds; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(){ HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setShowSql(Boolean.TRUE); vendorAdapter.setDatabase(Database.MYSQL); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setDataSource(dataSource()); factory.setPackagesToScan("com.springJpa.entity"); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy"); jpaProperties.put("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect"); factory.setJpaProperties(jpaProperties); factory.afterPropertiesSet(); return factory; } @Bean public SharedEntityManagerBean entityManager() { SharedEntityManagerBean entityManager = new SharedEntityManagerBean(); entityManager.setEntityManagerFactory(entityManagerFactory().getObject()); return entityManager; } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory().getObject()); return txManager; } @Bean public ImprovedNamingStrategy namingStrategy(){ return new ImprovedNamingStrategy(); } }
这是我的Entity类:
@Getter @Setter @Entity @Table(name="user") public class User{ @Id @GeneratedValue private Long id; private String userName; private String email; private String password; private String role; }
我不想在@Column批注中显式命名我的数据库字段。我希望我的配置可以将驼峰式大小写转换为下划线。
请指导。
刚发现问题,使用Hibernate版本<5.0的配置绝对可以,但是对于Hibernate> = 5.0的配置则不是。
我在Spring 4.2.0.RELEASE中使用了Hibernate 5.0.0.Final。我猜Hibernate 5与Spring 4.2不完全兼容。我只是将Hibernate降级为4.2.1,最终一切正常。
NamingStrategyHibernate 5中不推荐使用Hibernate的类。
NamingStrategy