Estoy desarrollando una aplicacion con springboot, hibernate en JAVA. Tengo el siguiente método
@PostMapping(AdminUrl.PAYMENT_TERMS)
public ResponseEntity savePaymentTerm(@Valid PaymentTerm paymentTerm, TableTranslationsWrapper tableTranslationsWrapper, @Valid ErpMappingWrapper erpMappingList, BindingResult bindingResult, Locale locale) {
if (bindingResult.hasErrors()) {
this.logErrors(bindingResult);
}
boolean isNew = paymentTerm.getCode() == null;
if (isNew && paymentTermRepository.existsByPaymentId(paymentTerm.getPaymentId())) {
String msg = messageSource.getMessage("validation.unique", new Object[]{paymentTerm.getPaymentId()}, locale);
return ResponseEntity.status(HttpStatus.CONFLICT).body(Utils.json("paymentId", msg));
}
paymentTerm = paymentTermRepository.saveAndFlush(paymentTerm);
if(isNew)
for(TableTranslations tt : tableTranslationsWrapper.getTableTranslationsList())
tt.getTableTranslationsPK().setCodeInTable(paymentTerm.getCode());
manageTableTranslations(tableTranslationsWrapper, PAYMENT_TERMS, paymentTerm.getCode());
manageErpMappings(erpMappingList.getErpMappingList(), isNew, PAYMENT_TERMS, paymentTerm.getCode());
return getResponse(paymentTerm, "validation.create.paymentterm.500", locale, isNew);
}
El método "manageTableTranslations" guarda en base de datos unas traducciones del campo descripción en diferentes idiomas. Estas traducciones las introduce el usuario manualmente.
El método "manageErpMapping" guarda también en base de datos.
El problema es que el segundo método, la entidad que graba "ErpMapping" es de tipo Loggable. Al guardar el log, accede a las traducciones guardadas en el otro método para registrar el log. Por razones de arquitectura, el método que recupera las traducciones, está dentro de la entidad a grabar
@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "PAYMENT_TERMS", uniqueConstraints = {
@UniqueConstraint(columnNames = {"PAYMENT_ID"})})
public class PaymentTerm implements Serializable, Loggable {
private static final long serialVersionUID = 1L;
private static final int tableNamePaymentTerm = 2;
@Id
@Column(name = "CODE", nullable = false)
@GenericGenerator(
name = "payment_terms",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "GEN_PAYMENT_TERMS"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "payment_terms")
private Long code;
@Column(name = "PAYMENT_ID")
private Short paymentId;
@Size(max = 100)
@Column(name = "DESCRIPTION", length = 100)
private String description;
@Column(name = "ACTIVE")
private Boolean active;
@JoinColumn(name = "CODE_IN_TABLE", referencedColumnName = "CODE", updatable = false, insertable = false)
@Where(clause = "TABLE_NAME = " + tableNamePaymentTerm)
@OneToMany
private Collection<ErpMapping> erpMapping;
public PaymentTerm() {
}
{getters y setters}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PaymentTerm)) return false;
PaymentTerm that = (PaymentTerm) o;
return Objects.equals(code, that.code) &&
Objects.equals(paymentId, that.paymentId) &&
Objects.equals(description, that.description) &&
Objects.equals(active, that.active);
}
@Override
public int hashCode() {
return Objects.hash(code, paymentId, description, active);
}
@Override
public String toString() {
return "entities.PaymentTerms[ code=" + code + " ]";
}
@Override
public String getDisplayName() {
return String.format("%s <%s>", getLocaleDescription(), getPaymentId());
}
@Override
public String toLoggablePrimaryKeyString() {
return getCode().toString();
}
@Override
public String toLoggableString() {
return String.valueOf(getPaymentId());
}
@Override
public String toLoggableDisplayName() {
return String.format("%s", getLocaleDescription());
}
public String getLocaleDescription(){
User user = ((UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
TableTranslationRepository tableTranslationRepository = (TableTranslationRepository) MainConfig.contextProvider().getApplicationContext().getBean("tableTranslationRepository");
TableTranslations tableTranslation = tableTranslationRepository.findByTableTranslationsPK_tableNameAndTableTranslationsPK_codeInTableAndTableTranslationsPK_language(PAYMENT_TERMS, getCode(), user.getLanguage().getCode());
if(tableTranslation == null)
return getDescription();
return tableTranslation.getTranslation();
}
}
El método "getLocaleDescription" recupera esa traducción, pero esta llamada "tableTranslationRepository.findByTableTranslationsPK_artemisTableAndTableTranslationsPK_codeInTableAndTableTranslationsPK_language(PAYMENT_TERMS, getCode(), user.getLanguage().getCode());" da error porque intenta hacer un merge de los datos actuales en base de datos con los que se intentan grabar.
¿Hay alguna manera de persistir esos datos definitivamente para que se puedan recuperar después?
He probado con las anotaciones "Transactional" con "isolation" y "propagation", pero no he obtenido ningún resultado. El proceso no falla allí, pero se queda colgado en ese método.
¿Alguna idea?
Edit:
private void manageTableTranslations(TableTranslationsWrapper tableTranslationsWrapper, TableName tableName, Long code) {
if(tableTranslationsWrapper == null)
return;
tableTranslationRepository.save(tableTranslationsWrapper.getTableTranslationsList());
List<TableTranslations> currentList = tableTranslationRepository.findByTableTranslationsPK_artemisTableAndTableTranslationsPK_codeInTable(tableName, code);
tableTranslationsWrapper.getTableTranslationsList().stream()
.filter(o1 -> currentList.stream().anyMatch(o2 -> o1.equals(o2)))
.forEach(currentList::remove);
tableTranslationRepository.delete(currentList);
}
private void manageErpMappings(List<ErpMappingSaveObject> erpMappingList, boolean isNew, TableName tableName, Long codeInTable){
erpMappingList.removeIf(erpMapping -> erpMapping.getErpMapping().getCodeInErp().isEmpty());
List<ErpMapping> erpMappingToSave = erpMappingList.stream().map(erpMap -> erpMap.getErpMapping()).collect(Collectors.toList());
List<ErpMapping> currentList = erpMappingRepository.findByErpMappingPK_tableNameAndErpMappingPK_codeInTable(tableName, codeInTable);
if(isNew){
erpMappingToSave.forEach((erpMapping) -> {
erpMapping.getErpMappingPK().setCodeInTable(codeInTable);
});
}
erpMappingRepository.save(erpMappingToSave);
if(!isNew){
erpMappingToSave.stream()
.filter(o1 -> currentList.stream().anyMatch(o2 -> o1.getErpMappingPK().equals(o2.getErpMappingPK())))
.forEach(currentList::remove);
erpMappingRepository.delete(currentList);
}
}
Cuando hace el "save" en "manageErpMapping", al grabar la entidad ErpMapping que es loggable, se lanza el grabado del Log. Se captura en el siguiente método y al recuperar "getLoggableString" se embucla.
public void logMasterData(LogModif logModif) {
Action action = logModif.getTypeModif();
String table = logModif.getEntity().getClass().getAnnotation(Table.class).name();
TableName tableName = TableName.valueOf(table);
String unilabelId;
if(tableName.equals(TableName.ERP_MAPPING)) {
// Les ERP_MAPPINGS me désespére...
ErpMapping erpMapping = (ErpMapping)logModif.getEntity();
ErpMappingPK erpMappingPk = (erpMapping).getErpMappingPK();
String companyId = "";
Optional<Object> obj = erpMappingService.getEntity(erpMappingPk.getTableName(), erpMappingPk.getCodeInTable());
if(obj.isPresent()) {
switch (erpMappingPk.getTableName()){
case BRANDS:
case PRINTSHOPS:
case WORKSHOPS:
case TRANSPORTATIONS:
companyId = ((Company)obj.get()).getCompanyId();
break;
case PRODUCTS:
case PAYMENT_TERMS:
case COUNTRIES:
companyId = ((Loggable)obj.get()).toLoggableDisplayName();
break;
default:
companyId = ((Loggable)obj.get()).getDisplayName();
break;
}
}
unilabelId = String.format("%s - %s",
companyId,
erpMapping.getErp().getDisplayName()
);
} else {
unilabelId = logModif.getEntity().toLoggableString();
}
List<MasterDataLog> masterDataLogs = new ArrayList<>();
// CREATE or DELETE
if(logModif.getLogsEntityModifs().isEmpty()) {
masterDataLogs.add(new MasterDataLog(artemisTable, action, unilabelId));
}
// UPDATE
else {
logModif
.getLogsEntityModifs()
.forEach(
logEntityModif -> {
TableName complexeType = null;
String value;
try {
complexeType = TableName.valueOf(((Table)logEntityModif.getType().getReturnedClass().getAnnotation(Table.class)).name());
value = ((Loggable)logEntityModif.getValue()).toLoggablePrimaryKeyString();
} catch (Exception e) {
value = logEntityModif.getValue().toString();
}
masterDataLogs.add(new MasterDataLog(tableName, action, unilabelId, logEntityModif.getPropertyName(), value, complexeType));
}
);
}
masterDataLogRepository.save(masterDataLogs);
}
merge
es un simple join que no debería tene problemasmanageTableTranslations
ymanageErpMapping
?ErpMapping
tiene un ` join` (@ManyToOne) conPaymentTerm
, es decir, si es una relación bidireccional.