实体使用表 id 生成器策略:
@Id
@TableGenerator(name = "id_gen",
table = "id_gen",
pkColumnName = "gen_name",
valueColumnName = "gen_val",
pkColumnValue = "shared_id_generator", /*same as generator name by default*/
initialValue = 10, /*0 by default*/
allocationSize = 100 /*50 by default*/)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "id_gen")
private long id;
所有实体都使用相同的策略和相同的生成器,因此我将表生成器定义移动到 jpa-mapping xml 文件中。Maven项目中的位置:
main/resources/db/jpa/orm.xml
生成器现在在 jpa-mapping xml 文件中定义为:
<table-generator name="id_shared_generator"
table="id_gen"
pk-column-name="gen_name"
pk-column-value="shared_id_value"
value-column-name="gen_val"
initial-value="10"
allocation-size="100" />
现在实体具有以下 id 字段:
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "id_shared_generator")
private long id;
我根本不使用 persistence.xml 文件,而是配置 entityManagerFactory:
@Bean
@DependsOn("liquibase")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
// emfb.setPersistenceXmlLocation("classpath:META-INF/persistence.xml");
emfb.setPackagesToScan(new String[]{"com.savdev.springmvcexample.domain"});
emfb.setMappingResources("db/jpa/orm.xml");
emfb.setJpaVendorAdapter(jpaVendorAdapter());
emfb.setJpaProperties( new Properties(){{
put("hibernate.hbm2ddl.auto", "validate");
put("hibernate.format_sql", "true");
put("hibernate.show_sql", "true");
}});
emfb.setPersistenceUnitName("springmvcexample");
return emfb;
}
现在我在尝试加载 spring 应用程序上下文时遇到以下异常:
原因:org.springframework.beans.factory.BeanCreationException:创建类路径资源[spring/repository-config.xml]中定义的名称为“entityManagerFactory”的bean时出错:调用init方法失败;嵌套异常是 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory ... 原因:org.hibernate.AnnotationException: Unknown Id.generator: id_shared_generator
请告诉我,我做错了什么?是否允许通过emfb.setMappingResources("db/jpa/orm.xml");
调用设置额外的 jpa 映射 xml 文件?