Dealing with nullable UUID in a controller - SpringBoot and Postgres - spring-boot

I have an entity that includes a nullable UUID (but it is not an ID), as follows:
#Column(nullable = true)
var myField: UUID? = null
I also have a dto converter as follows:
myField = entity.myField.let { it }
I can correctly store a null value for the UUID field, but when inspecting the GET response from my controller whenever I pass a null value for such field the body does not contain the myField at all. What is the reason for that? How does SpringBoot deal with null value for UUID.
Thanks

Related

#Value on R2dbc table fields

Given the following entity/table defined in a Spring/KotlinCoroutines project.
#Table("workers")
data class Worker(
#Id
val id: UUID? = null,
#Column(value = "photo")
var photo: String? = null,
// see: https://github.com/spring-projects/spring-data-r2dbc/issues/449
#Transient
#Value("#{root.photo!=null}")
val hasPhoto: Boolean = false
)
The hasPhoto field does not map to a table field. I follow the R2dbc official reference doc and use a Spring EL to evaluate the EL result as value of this field.
But when I test this hasPhoto, it always returns false even I set the photo to a nonnull string.
Got answer from the Spring guys, #Value here only can access the projection.

Spring Data JPA projection issue with field starting with IS in kotlin

I'm using interface based projection to get certain fields from db. one of my field name start with is. I'm able to get the field from database via native query, however, the response returned by spring boot controller does not contain is in field name. How should I resolve it?
interface UserProjection {
val userId: Long
val isPrivate: Boolean
val likesCount: Int
}
Query
SELECT u.user_id as userId, u.is_private as private, u.likes_count as likesCount FROM users u WHERE u.user_id=?;
However, response returned by spring boot is
{
"userId": 12345,
"private": false,
"likesCount": 1
}
The solution is to use a fun to get the field instead of a val
interface LoginUserProjection {
val id: Long
val passwordHash: String
fun getIsVerifiedAccount(): Boolean
}

DB field empty problems in Spring Boot

I have a method in Spring Boot that collects various database dates from the logged in employee.
private boolean isActiveThisMonth(EmployeeView emp,LocalDate date){
return (emp.getHiringDate().withDayOfMonth(1).minusDays(1).isBefore(date.withDayOfMonth(1)) && (emp.getLeavingDate()==null ||
emp.getLeavingDate().plusMonths(1).withDayOfMonth(1).isAfter(date.with(lastDayOfMonth()))));
}
Currently if the hiringDate field is empty in the database, it returns an error. How can I add an exception so that if the field arrives without an error? Or if it is better to put a date, for example the current day and thus not an error?
A couple of ways to prevent this.
1.
You could handle the null value inside isActiveThisMonth like this
private boolean isActiveThisMonth(EmployeeView emp,LocalDate date){
LocalDate hiringDate = emp.getHiringDate() != null ? emp.getHiringDate() : LocalDate.now();
return (hiringDate.withDayOfMonth(1).minusDays(1).isBefore(date.withDayOfMonth(1)) && (emp.getLeavingDate()==null ||
emp.getLeavingDate().plusMonths(1).withDayOfMonth(1).isAfter(date.with(lastDayOfMonth()))));
}
You could make sure the value is set in the Entity when the Employee is created.
#Column(name = "hire_date", columnDefinition = "DATE DEFAULT CURRENT_DATE")
private jDate startDate;

How to check if UUID is null, empty or blank?

I have a Springboot application and my entity have a field id and ownerId which is type of UUID.
How can i check if the UUID is actually a UUID and not a string or anything else?
My example code:
when {
project.id != null -> handleIllegalParameter("id")
project.ownerId != null -> handleIllegalParameter("ownerId")
project.name.isNullOrBlank() -> handleMissingRequiredField("name")
}
How can I can check that is actually a UUID and not a string, integer or anything else except UUID?
If your id and ownerId are of type UUID? then once you check they are not null - you are good. If they of type String (as the title of your question implies) you can use the UUID.fromString() method that throws IllegalArgumentException if the conversion fails.

How to query documents with null values MongoRepository Spring Data MongoDB

I couldn't initialise the value to be false in Spring Data MongoDB, so in my query, I want to search documents with field set to false or null.
The following snippet doesn't seem to work:
#RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveFalseOrIsActiveNull(#Param("id"))
I'm not sure you can achieve such query using Spring data method name. Since your query will be evaluated as _id == "id" AND isActive == false OR isActive == null and not _id == "id" AND ( isActive == false OR isActive == null ).
If by chance isActive can only be true, false or null, you could try
#RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveNot(#Param("id"), true)
Otherwise, you will need to use other query method provided by Spring data mongodb such as MongoTemplate helper class or #Query annotation.
#Query annotation
#RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
#Query("{$and: [{'_id': :#{#id}}, $or: [{ 'isActive':false}, {'isActive': null}]]}")
Order findByIdAndIsActiveNot(#Param("id"))

Resources