繁体   English   中英

如何防止使用 Hibernate + JPA 执行不需要的更新语句

[英]How to prevent unwanted update statements being executed using Hibernate + JPA

我有 2 个实体空间和类型。 它们都相互关联。 使用这些对象时,当代码执行甚至非常简单的操作时,我会遇到许多不需要的更新语句。

我在下面放了一个简单的场景。 而且,我的应用程序(Spring Boot API)中正在执行一些更复杂的批处理操作。 而且,这个问题导致所有链接的实体都被更新,即使它们没有被修改。

我需要以某种方式摆脱这些不需要的更新,因为它们会导致某些操作出现严重的性能问题。

空间实体(部分显示):

@Entity
@Table(name = "spaces")
@Getter
@Setter
@NoArgsConstructor
public class SpaceDao {
        @Id
        @GeneratedValue(generator = "uuid")
        @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
        private byte[] uuid;

        @ManyToOne
        @JoinColumn(name = "type_id")
        private TypeDao type;
}

类型实体(部分显示):

@Entity
@Table(name = "types")
@Getter
@Setter
@NoArgsConstructor
public class TypeDao {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
  
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="space_id")
    private SpaceDao space;
}

Space repo 实现中的 Save 方法:

public Space saveSpace(Space space) {
    SpaceDao spaceDao = SpaceMapper.toDao(space);

    // Intentionally simplified this logic, to point out that
    // I am only reading and saving the object, without any changes.
    SpaceDao existingSpaceDao = relationalSpaceRepository.findById(spaceDao.getUuid()).get();
    // Following line is where the magic happens
    SpaceDao savedSpaceDao = relationalSpaceRepository.save(existingSpaceDao);

    return SpaceMapper.toModelObject(savedSpaceDao, true);
}

空间 crud 存储库:

public interface RelationalSpaceRepository extends CrudRepository<SpaceDao, byte[]> { }

代码命中 repository.save() 行时生成的休眠日志:

Hibernate: update spaces set description=?, location=?, name=?, parent_id=?, properties=?, status_id=?, status=?, subtype_id=?, subtype=?, type_id=?, type=? where uuid=?
Hibernate: update spaces set description=?, location=?, name=?, parent_id=?, properties=?, status_id=?, status=?, subtype_id=?, subtype=?, type_id=?, type=? where uuid=?
Hibernate: update types set category=?, definition=?, description=?, disabled=?, logical_order=?, name=?, space_id=? where id=?
Hibernate: update types set category=?, definition=?, description=?, disabled=?, logical_order=?, name=?, space_id=? where id=?
Hibernate: update spaces set description=?, location=?, name=?, parent_id=?, properties=?, status_id=?, status=?, subtype_id=?, subtype=?, type_id=?, type=? where uuid=?
Hibernate: update spaces set description=?, location=?, name=?, parent_id=?, properties=?, status_id=?, status=?, subtype_id=?, subtype=?, type_id=?, type=? where uuid=?
Hibernate: update types set category=?, definition=?, description=?, disabled=?, logical_order=?, name=?, space_id=? where id=?
Hibernate: update spaces set description=?, location=?, name=?, parent_id=?, properties=?, status_id=?, status=?, subtype_id=?, subtype=?, type_id=?, type=? where uuid=?
Hibernate: update types set category=?, definition=?, description=?, disabled=?, logical_order=?, name=?, space_id=? where id=?
Hibernate: update spaces set description=?, location=?, name=?, parent_id=?, properties=?, status_id=?, status=?, subtype_id=?, subtype=?, type_id=?, type=? where uuid=?

找到原因和解决办法。

这是由误报脏检查引起的。 我不确定为什么,但在从数据库中检索实体后,引用类型的属性值会重新实例化,我相信。 导致脏检查将这些实体视为已修改。 因此,下次刷新上下文时,所有“修改过的”实体都将持久保存到数据库中。

作为解决方案,我实现了一个自定义的 Hibernate 拦截器,扩展了 EmptyInterceptor。 并将其注册为hibernate.session_factory.interceptor 这样,我就可以进行自定义比较并手动评估脏标志。

拦截器实现:

@Component
public class CustomHibernateInterceptor extends EmptyInterceptor {

    private static final long serialVersionUID = -2355165114530619983L;

    @Override
    public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
            String[] propertyNames, Type[] types) {
        if (entity instanceof BaseEntity) {
            Set<String> dirtyProperties = new HashSet<>();
            for (int i = 0; i < propertyNames.length; i++) {
                if (isModified(currentState, previousState, types, i)) {
                    dirtyProperties.add(propertyNames[i]);
                }
            }

            int[] dirtyPropertiesIndices = new int[dirtyProperties.size()];
            List<String> propertyNamesList = Arrays.asList(propertyNames);
            int i = 0;
            for (String dirtyProperty : dirtyProperties) {
                dirtyPropertiesIndices[i++] = propertyNamesList.indexOf(dirtyProperty);
            }
            return dirtyPropertiesIndices;
        }

        return super.findDirty(entity, id, currentState, previousState, propertyNames, types);
    }

    private boolean isModified(Object[] currentState, Object[] previousState, Type[] types, int i) {
        boolean equals = true;
        Object oldValue = previousState[i];
        Object newValue = currentState[i];

        if (oldValue != null || newValue != null) {
            if (types[i] instanceof AttributeConverterTypeAdapter) {
                // check for JSONObject attributes
                equals = String.valueOf(oldValue).equals(String.valueOf(newValue));
            } else if (types[i] instanceof BinaryType) {
                // byte arrays in our entities are always UUID representations
                equals = Utilities.byteArrayToUUID((byte[]) oldValue)
                        .equals(Utilities.byteArrayToUUID((byte[]) newValue));
            } else if (!(types[i] instanceof CollectionType)) {
                equals = Objects.equals(oldValue, newValue);
            }
        }

        return !equals;
    }
}

在配置中注册:

@Configuration
public class XDatabaseConfig {

    @Bean(name = "xEntityManagerFactory")
    @Primary
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        CustomHibernateInterceptor interceptor = new CustomHibernateInterceptor();
        vendorAdapter.setGenerateDdl(Boolean.FALSE);
        vendorAdapter.setShowSql(Boolean.TRUE);
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.x.dal.relational.model");
        factory.setDataSource(xDataSource());
        factory.getJpaPropertyMap().put("hibernate.session_factory.interceptor", interceptor);
        factory.afterPropertiesSet();
        factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
        return factory.getObject();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM