2017-06-15 19 views
4

単項演算子を使用してJPAでブール値を設定できるかどうかを知りたい。 私は有効フィールドは、これは結果JPA単項演算子

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] 
ある boolean(1)

として格納されているDBでPOJO

private Boolean enabled; 

public Boolean getEnabled() { 
    return enabled; 
} 

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

でこのようにマッピングされている。この

@Modifying 
@Query("update 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を使用していることfalseまたはtrueとして01を区別することはできません。

@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のフィールドを変更するには、次のようになります。

あなたがJPA 2.1を使用している場合は、私は、boolean型変換のためのグローバルなコンバータを作成することをお勧め:

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

2番目のソリューションでアプリケーションを起動するとエラーは発生しませんが、フィールドが正しく更新されません –

+0

例を挙げることはできますか? –

関連する問題