【问题标题】:How to prevent unwanted update statements being executed using Hibernate + JPA如何防止使用 Hibernate + JPA 执行不需要的更新语句
【发布时间】:2020-09-23 12:55:46
【问题描述】:

我有 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 实现中的保存方法:

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);
}

空间碎片存储库:

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=?

【问题讨论】:

  • 需要更多信息,例如这些检测到的差异来自何处。我怀疑使用 find 读取的 SpaceDao 在您调用 find 到调用 save 之间变得陈旧 - 如果您使用类似合并的操作,则会出现问题。您需要确保保留最初在 SpaceDao 中读取的上下文以用于保存操作,因为它可用于跟踪您所做的实际差异,而不必检测它与当前内容之间的差异调用 save 时的数据库。
  • 如果我没记错的话,JPA 是基于托管实体的。因此,每当您在会话中对托管实体应用一些更改时,它们将在您刷新/关闭会话时保持不变。您确定更新不是来自会话管理吗?编辑:但您似乎没有应用任何更改...
  • SpaceDao 和 TypeDao 有多对一的关系,而 type 和 SpaceDao 也有多对一的关系,这种关系是正确的还是多对多的关系?
  • 两次多对一关系非常可疑。此外,仅在一侧(ManyToOne 一侧)使用 @JoinColumn。
  • @Chris,嗯,就像repo实现方法中展示的那样简单。这不合逻辑,但我简化了它以首先测试这种情况下的可能解决方案。如所见,在读取和写入之间没有修改或任何其他操作。此外,Spring Data 的 CrudRepository 默认使用 findById() 和 save() 方法。

标签: java spring hibernate jpa


【解决方案1】:

找到原因和解决办法。

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

作为一种解决方案,我实现了一个自定义的 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();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2012-12-15
    • 1970-01-01
    • 2019-10-04
    • 2011-11-22
    • 2019-12-10
    相关资源
    最近更新 更多