serkanz
serkanz

Reputation: 451

Persisting Set<Enum> with Integer value on MongoDB

I have a Notification class which contains a Set<NotificationType> field notificationType.

When I try to make an insert operation of an instance of Notification to INotificationRepository that extends MongoRepository<Notification, String> notificationType field in Mongo is populated with the constant of enum NotificationType (like ["FEED","NOTIFICATION"]). I expect it to be persisted as [0,3].

How could I persist the value field of the enum to MongoDB?

@Document
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Notification {
    @Id
    private String id;

    @Indexed
    private Set<NotificationType> notificationType;
}

@AllArgsConstructor
@Getter
public enum NotificationType {
    FEED(0,"Feed"),
    SMS(1, "Sms"),
    EMAIL(2, "Email"),
    NOTIFICATION(3, "Notification");

    private final Integer value;
    private final String text;
}


Upvotes: 0

Views: 324

Answers (1)

Vinh Truong
Vinh Truong

Reputation: 431

I don't usually work with MongoDB, but maybe you can use AttributeConverter
For example:

@Converter
public class NotificationTypeConverter implements AttributeConverter<Notification, Integer> {
    @Override
    public Integer convertToDatabaseColumn(NotificationType attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getValue();
    }

    @Override
    public NotificationType convertToEntityAttribute(Integer dbData) {
       // convert from Integer to enum
    }
}

And add @Convert to notificationType field:

@Convert(converter = NotificationTypeConverter.class)
private Set<NotificationType> notificationType;

Upvotes: 1

Related Questions