2017-06-15 43 views
4

我想知道是否可以使用一元運算符在JPA中設置布爾值。 我的意思是這樣JPA一元運算符

@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; 
} 
在DB

它被存儲爲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屬性

春數據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 
+0

你有什麼錯誤嗎?或者它根本不適合你? –

+0

你可以添加計算機映射類嗎?特別是布爾型字段。 –

+0

表中列的數據類型是什麼? –

回答

3

不同的數據庫對布爾表達式的處理不同的支持,所以很少有餘地JPA提供一個通用的方法,因此你必須要明確:

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

可能是你在MySQL的側爲該列和持久性提供使用tinyint不能區分01falsetrue

如果您正在使用JPA 2.1那麼我會建議創建布爾轉換一個全球性的轉換器:

@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); 
    } 
} 

有點開箱替代將改變POJO領域的整數和查詢更改爲以下:

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

與第二個解決方案我沒有錯誤,當我啓動應用程序,但它不正確更新字段 –

+0

你可以舉個例子嗎? –