好的,我想通了。在 Spring Boot 中,有一种方法可以覆盖 persistence.xml 文件中的默认持久性映射。我们首先需要像这样在应用配置中创建一个 bean(entityManagerFactory 名称应该在那里,因为 spring 会寻找它):
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(springJpaDataSource());
factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
if(!db_url.contains("oracle"))// something that tells you it's not oracle
{
factory.setPersistenceXmlLocation("classpath:jpa/custom-persistance.xml");
}
else{
// this file will not contain any mapping files to override ID generation
factory.setPersistenceXmlLocation("classpath:jpa/custom-persistance-oracle.xml");
}
return factory;
}
现在添加文件(custom-persistance.xml):
<persistence
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<provider>
org.hibernate.jpa.HibernatePersistenceProvider
</provider>
<mapping-file>
jpa/entity-mappings.xml
</mapping-file>
</persistence-unit>
对于 custom-persistance-oracle.xml 文件将与没有映射文件 xml 标记的文件相同。然后添加具有映射的实际文件:
<entity-mappings
xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm"
version="2.1">
<package>com.example.pcakageto.classes</package>
<entity class="ClassA" access="FIELD">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
</attributes>
</entity>
<entity class="ClassB" access="FIELD">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
</attributes>
</entity>
最后,Java 文件中的 ID 映射应该像往常一样使用序列:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
@SequenceGenerator(name="id_generator", sequenceName = "sequence_name", allocationSize=1)
private Integer id;