-1

I'm trying to make a mongo query (using Spring Data) for searching record by the Option value from Vavr. I have value Option userId and I'm wondering if it's possible to search in database by this parameter.

I have serched in MongoDB and Spring documentation, but in none of this is anything about Vavr type like Option. None of this query are working.

Option<Result> FindFirstByUserIdAndCreationDateDesc(String userId);

Option<Result> FindFirstByOptionUserIdAndCreationDateDesc(String userId);

where userId is Vavr Option

Option<String> userId;

1 Answers1

1

Vavr's Option and Java's Optional are types for eliminating the null value.

Database don't use optional values, they use null values, so unwrap the value to a null.

userId.getOrElse(null)

However, be aware that in e.g. SQL databases, the null value doesn't compare equal to itself, so a WHERE userId = ? will return nothing if the ? argument is null. To find records with a null value, the SQL must be WHERE userId IS NULL, so unless your FindXxx methods knows this and account for it, the code will still not work for you.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • SQL treatment of null is irrelevant to this question. – Bohemian May 26 '19 at 23:40
  • Thanks, but the problem is in the saving objects in repository. If I save object with Option value, for example class User, with Option userId value, its impossible (probably) to make proper query to search in database by this userId. – Mateusz Kwiecień May 27 '19 at 06:33
  • @MateuszKwiecień If the value of `userId` in the database is an `Option`, then of course you need to search the database using an `Option`, not a `String`, because `Option` and `String` are two different types. Which part of that is difficult to understand? I mean, if the value on the database was a `Long`, would you try to search using a `BigDecimal`? Of course not, because `Long` and `BigDecimal` will never compare equal. Neither will `Option` and `String`. – Andreas May 27 '19 at 22:30