Unary JPA Operators
I want to know if it is possible to set a boolean value in JPA using the Unary Operator. I mean something like this
@Modifying
@Query("update Computer com set com.enabled=!com.enabled where com.id = ?1")
Allowed field is displayed this way in POJO
private Boolean enabled;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
stored in the database as boolean(1)
this is the result
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: expecting '=', found 'c' [update com.nicinc.Computer com set com.enabled=!com.enabled where com.id = ?1]
and here the JPA properties
Spring JPA Data Properties
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
source to share
You are probably using tinyint
MySQL side for this column and the persistence provider cannot distinguish between 0
and 1
how false
or true
.
If you are using JPA 2.1
, I would suggest creating a global boolean converter:
@Converter(autoApply=true)
public class GlobalBooleanConverter implements AttributeConverter<Boolean, Integer>{
@Override
public String convertToDatabaseColumn(Boolean value) {
if (Boolean.TRUE.equals(value)) {
return Integer.valueOf(1);
} else {
return Integer.valueOf(0);
}
}
@Override
public Boolean convertToEntityAttribute(String value) {
return Integer.valueOf(1).equals(value);
}
}
An alternative to selection could be to change the POJO field to Integer and change the query like this:
@Modifying
@Query("update Computer com set com.enabled=((-com.enabled)+1) where com.id = ?1")
source to share