user2693135
user2693135

Reputation: 1316

JPA Enumeration Query

I'm using Spring Data JPA. I have a Recipe entity and a Difficulty enum with properties, EASY, MEDIUM, HARD.

My Recipe class is composed of Difficulty, as shown below:

@Enumerated(value=EnumType.STRING)
private Difficulty difficulty;

My code works as expected, and I am able to save a Recipe with a difficulty.

My question starts here. What if i want to add multiple enums to one db column? e.g so i want a recipe to have lets say two of these difficulties.

Upvotes: 0

Views: 182

Answers (1)

RJ.Hwang
RJ.Hwang

Reputation: 1913

Use custom AttributeConverter :

@Convert(converter = DifficultiesConverter::class)
private List<Difficulty> difficulties;


import javax.persistence.AttributeConverter
@Converter(autoApply = true)
public class DifficultiesConverter implements AttributeConverter<List<Difficulty>, String> {
  public String convertToDatabaseColumn(List<Difficulty> attribute) {
    // convert List to String, such as [EASY, MEDIUM, ...] to "EASY,MEDIUM,..."
    return ... 
  }

  public List<Difficulty> convertToEntityAttribute(String dbData) {
    // convert String to List, such as "EASY,MEDIUM,..." to [EASY, MEDIUM, ...]
    return ... 
  }
}

Upvotes: 1

Related Questions