Hibernate全局“动态插入”

3j86kqsm  于 2022-11-14  发布在  其他
关注(0)|答案(3)|浏览(144)

有没有办法用Hibernate全局设置dynamic-insert属性(因此它将成为所有实体的默认属性)?

fhg3lkii

fhg3lkii1#

在NHibernate中,它是

foreach (var clazz in config.ClassMappings)
{
    clazz.DynamicInsert = true;
}

我不知道Hibernate中的确切语法。

for (PersistentClass clazz : configuration.ClassMappings)
{
    clazz.setDynamicInsert(true);
}
hgqdbh6s

hgqdbh6s2#

对于Java Hibernate,正确答案是:

Iterator mappingClasses = config.getClassMappings();
while(mappingClasses.hasNext()) {
   PersistentClass clazz = (PersistentClass) mappingClasses.next();
   clazz.setDynamicInsert(true);
   clazz.setDynamicUpdate(true);
}

请记住,您必须在尝试迭代Map之前构建Map。否则,config.getClassMappings()将返回空迭代器。

config.buildMappings();
y53ybaqx

y53ybaqx3#

您可以编写一个简单的集成器来读取sistence.xml并修改Hibernates引导元数据:

import org.hibernate.boot.Metadata;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.immutables.metainf.Metainf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Metainf.Service(Integrator.class)
public class DynamicUpdateIntegrator implements Integrator {
  private static final String SETTING = "hibernate.dynamic_update";
  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory,
      SessionFactoryServiceRegistry serviceRegistry) {
    ConfigurationService cfgService = serviceRegistry.getService(ConfigurationService.class);
    Boolean shouldUseDynamicUpdate = cfgService.getSetting(SETTING, StandardConverters.BOOLEAN, null);
    if (shouldUseDynamicUpdate == null) {
      return;
    }

    logger.info("Setting dynamic update to {} for all entities.", shouldUseDynamicUpdate);
    for (PersistentClass persistentClass : metadata.getEntityBindings()) {
      persistentClass.setDynamicUpdate(shouldUseDynamicUpdate);
    }
  }

  @Override
  public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {}
}

然后将此行添加到您的Persistence.xml中:

<property name="hibernate.dynamic_update" value="true" />

请注意,此代码使用注解处理器org.immutables:metainf:2.9.0DynamicUpdateIntegrator的完全限定类名添加到文件META-INF/services/org.hibernate.integrator.spi.Integrator。您可以使用https://github.com/google/auto/tree/master/service来实现相同的功能,也可以手动创建和更新该文件。

相关问题