2

I wonder if it's posible to map Enum VARIABLE and DB. I want to save in database the yellow values (variables of enum)

Enum variable

The enum is used in this class:

@Getter
@Setter
@Table(name = "TIPOS_MOVIMIENTO")
@Entity

public class TipoMovimiento {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column
@Enumerated(EnumType.STRING)
private TipoMov tipo;

public String getTipo() {
    return tipo.getTipoNombre();
}

@OneToMany(mappedBy = "tipoMov")
private List<Movimiento> movimientos;

My DTO class:

@Getter
public class TipoMovimientoDto implements DtoEntity {

private TipoMov tipo;

}

I've tried DTO with

@Convert(converter = TipoMovEnumConverter.class) private TipoMov tipo;

But it doesn't works

1 Answer 1

6

Write an AttributeConverter for your enum which will convert your enum data into it's value when store in database.

@Converter(autoApply = true)
public class TipoMovConverter implements AttributeConverter<TipoMov, String> {

  @Override
  public Integer convertToDatabaseColumn(TipoMov attribute) {
    return attribute.getTipoNombre();
  }

  @Override
  public TipoMov convertToEntityAttribute(String value) {
    return value == null ? null : TipoMov.findByValue(value);
  }
}

Note: Here findByValue is a static method to get enum from value string

Sign up to request clarification or add additional context in comments.

8 Comments

I didn't mention it but I had already tried a converter (You can see everything here: stackoverflow.com/questions/63237129/…). It was working perfectly but... I had to implement a DTO class for TipoMovimiento and... I didn't find a way to make it work with DTO :( So I decided to try other way that didn't use a converter.
There is a difference between converter and attribute converter, attribute converter work also if you directly fetch data from database as dto
What I did is an attribute converter, I'm kinda noob programmer and I may not explain well (sorry!) When I launch Postman output with Dto... it says: { "tipo": null }, { "tipo": null }, { "tipo": null },...... The only I have in my DTO is this: @Getter public class TipoMovimientoDto implements DtoEntity { private TipoMov tipo; } I've tried writing Enumerated... and other things... but doesn't works!
Did you try above solution with @Enumerated(EnumType.STRING) removed?
Yes @KavithakaranKanapathippillai I tried that yesterday stackoverflow.com/questions/63237129/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.