mercredi 29 janvier 2020

How to use AttributeConverter and @ElementCollection in a wrapped List using Hibernate?

I need to implement an API that provides custom data types to use in software development. The idea is that such types can give additional features to the default ones from Java language.

For example:

class ViewStringList {

  // String value
  private List<String> values = new ArrayList();

  // Define if the value must be show/hide on view
  private boolean visible;

  public List<String> getValues() {
    return values;
  }

  public void hide() {
    this.visible = false;
  }

  public void show() {
    this.visible = true;
  }

}

This custom type can be viewed as an extension from the Java List<String> type because it provides the hide and show feature. Using this type as Java property is fine because it facilitates development. However, if I want to persist each value from the ViewStringList list of values in a relational table using @ElementCollection and AttributeConverter I don't know how to do this. For example:

@Entity
class Panel {

  @ElementCollection
  private ViewStringList cars = new ViewStringList();

  @ElementCollection
  private ViewStringList trucks = new ViewStringList();

  // Getters/setters
}

class FormTemplate {

  public Panel getUserPanel() {
    Panel panel = new Panel();
    panel.getCars().show();
    panel.getTrucks().hide();
    return panel;    
  }

}

@Converter(autoApply = true)
class ViewStringConverter implemets AttributeConverter<ViewStringList, String> {

  @Override
  public String convertToDatabaseColumn(ViewStringList viewString) {
    return ?;
  }

  @Override
  public ViewStringList convertToEntityAttribute(String string) {
    return ?;
  }

}

Is that possible? There is some other strategy to achieve this persistence?

Aucun commentaire:

Enregistrer un commentaire