我找到了一种方法来解决我的问题,也可以是你的问题。
我正在调试我的代码,并在这些实体中找到了lojaMaster
, seguradora
and tabelaSeguro
一种称为处理程序的方法。我的问题是,该系统是在较旧的数据库中开发的。所以Envers
不会在他们的aud table
,并没有找到。
在这张图中你可以看到,处理程序是一个proxy object
并具有id
of the object
.
所以我开始尝试找到一种方法来得到这个Id
。所以当我明白这是一个proxy object
我在谷歌中找到了解决方案,而 Hibernate 使这成为一种不获取对象所有内容的策略。
所以我得到了代码,并得到了 id。
public Serializable getIdentifier(Object object) {
if (!(object instanceof HibernateProxy) || Hibernate.isInitialized(object)) {
return ((Persistent)object).getId();
}
HibernateProxy proxy = (HibernateProxy) object;
LazyInitializer initializer = proxy.getHibernateLazyInitializer();
return initializer.getIdentifier();
}
所以我得到并检查我的实体是否Id
is null
。我拿到了身份证,然后findById
the object
。我创建了一个hashmap
不要每次都访问database
因为ids
可以重复。
所以这些方法是这样的
@Override
public List<Pojo> getLog(Pojo pojo) {
Map<Long, Loja> mapLoja = new HashMap<>();
Map<Long, Seguradora> mapSeguradora = new HashMap<>();
Map<Long, TabelaSeguro> mapTabelaSeguro = new HashMap<>();
List<Pojo> auditedList = super.getLog(pojo);
if (!NullUtil.isNull(auditedList)) {
for (Pojo pojoAudited : auditedList) {
Long id = null;
if (NullUtil.isNull(pojoAudited.getLojaMaster().getId())) {
id = (Long) this.getIdentifier(pojoAudited.getLojaMaster());
this.getLojaRegister(mapLoja, id);
pojoAudited.setLojaMaster(mapLoja.get(id));
}
if (NullUtil.isNull(pojoAudited.getSeguradora().getId())) {
id = (Long) this.getIdentifier(pojoAudited.getSeguradora());
this.getSeguradoraRegister(mapSeguradora, id);
pojoAudited.setSeguradora(mapSeguradora.get(id));
}
if (NullUtil.isNull(pojoAudited.getTabelaSeguro().getId())) {
id = (Long) this.getIdentifier(pojoAudited.getTabelaSeguro());
this.getTabelaSeguroRegister(mapTabelaSeguro, id);
pojoAudited.setTabelaSeguro(mapTabelaSeguro.get(id));
}
}
}
return auditedList;
}
private void getLojaRegister(Map<Long, Loja> mapLoja, Long id) {
if (!mapLoja.containsKey(id)) {
Loja loja = this.findById(id);
mapLoja.put(id, loja);
}
}
private void getSeguradoraRegister(Map<Long, Seguradora> mapSeguradora, Long id) {
if (!mapSeguradora.containsKey(id)) {
Seguradora seguradora = this.getSeguradoraService().findById(id);
mapSeguradora.put(id, seguradora);
}
}
private void getTabelaSeguroRegister(Map<Long, TabelaSeguro> mapTabelaSeguro, Long id) {
if (!mapTabelaSeguro.containsKey(id)) {
TabelaSeguro tabelaSeguro = this.getTabelaSeguroService().findById(id);
mapTabelaSeguro.put(id, tabelaSeguro);
}
}
我希望这可以帮助有问题的人Envers
和旧数据库。