gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:00:47 25 4
gpt4 key购买 nike

我有 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 日志:

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

}

关于java - 如何防止使用 Hibernate + JPA 执行不需要的更新语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64028474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com