如何将枚举变量保存到数据库(而不是枚举值本身)

San*_*uky 2 java mapping enums spring-data

我想知道是否可以映射枚举变量和数据库。我想将黄色值(枚举变量)保存在数据库中

枚举变量

此类中使用了枚举:

@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;
Run Code Online (Sandbox Code Playgroud)

我的 DTO 课程:

@Getter
public class TipoMovimientoDto implements DtoEntity {

private TipoMov tipo;

}
Run Code Online (Sandbox Code Playgroud)

我尝试过 DTO

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

但这不起作用

Ekl*_*vya 6

为您的枚举编写一个AttributeConverter,它将在存储在数据库中时将您的枚举数据转换为其值。

@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);
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:这findByValue是一个从值字符串中获取枚举的静态方法