mysql - JPA 一元运算符

标签 mysql hibernate jpa spring-data-jpa h2

我想知道是否可以在 JPA 中使用一元运算符设置 bool 值。 我的意思是这样的

@Modifying
@Query("update Computer com set com.enabled=!com.enabled where com.id = ?1")    

启用字段在POJO中是这样映射的

private Boolean enabled;

public Boolean getEnabled() {
    return enabled;
}

public void setEnabled(Boolean enabled) {
    this.enabled = enabled;
}

在数据库中,它存储为 boolean(1)

这是结果

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]

这里是 JPA 属性

Spring Data JPA 属性

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

最佳答案

不同的数据库对 bool 表达式的处理有不同的支持,所以 JPA 提供通用方法的空间很小,因此你必须明确:

update Computer
set enabled = case when enabled = true then false else true end
where id = ?1

关于mysql - JPA 一元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44563550/

相关文章:

MYSQL:如果一个连接行符合条件,则排除多行

sql - 查询主键真的值得吗?

MySql 自然排序与某个值的偏移量

java - 为什么此 HQL 搜索查询不起作用?

java - Hibernate继承,父类应该根据决策者是子类还是父类

python - 如何在Sqlalchemy中加载数量有限的集合?

java - 为什么要在实体类中实现序列化

java - 当仅修改实体 obj 的少数字段且其余字段不应为空时,如何更新 Hibernate 实体记录

Java web 项目 + JPA/JDBC "Error connecting to server localhost on port 1527 with message Connection refused"

java - 无法使用 eclipse link 和 oracle db 生成表 - IllegalBlockSizeException