TypedQuery无法在where block中继续使用boolean

时间:2016-11-18 09:48:21

标签: java boolean hql

我的代码中有实体AnnouncementEntity:

public class AnnouncementEntity {

    //columns
    private long id;    
    ***
    private Boolean on;
    ***
    @Column(name="ACTIVE")
    public Boolean getOn() {
        return on;
    }

    public void setOn(Boolean on) {
        this.on = on;
    }
}

我试图获取所有“真实”的记录。在这个领域:

TypedQuery<AnnouncementEntity> query = 
em.createQuery("select p from AnnouncementEntity p where p.on = TRUE",       AnnouncementEntity.class);

但我面临例外:

SEVERE: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: p near line 1, column 60 [select p from com.ui4ivr.entity.AnnouncementEntity p where p.on = TRUE] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:313) at com.ui4ivr.dao.daoImpl.getAllAnnsVShort(daoImpl.java:933) at com.ui4ivr.view.MainView.enter(MainView.java:259)

你能说出来是什么问题吗?

1 个答案:

答案 0 :(得分:1)

根据您对ACTIVE列的定义,您应该相应地映射您的媒体资源:

  • org.hibernate.type.BooleanType将布尔值映射到JDBC BIT类型
  • org.hibernate.type.NumericBooleanType将布尔值映射到JDBC INTEGER类型为0 = false,1 = true
  • org.hibernate.type.YesNoType将布尔值映射到JDBC CHAR类型 (&#39; N&#39; |&#39; n&#39;)= false,(&#39; Y&#39; |&#39; y&#39;)= true
  • org.hibernate.type.TrueFalseType将布尔值映射到JDBC CHAR类型 as(&#39; F&#39; |&#39; f&#39;)= false,(&#39; T&#39; |&#39; t&#39;)= true

例如,如果您的ACTIVE列是CHAR(1)并且存储了&#39; Y&#39;或者&#39; N&#39;值,您应该在您的实体中定义相关方法:

//columns
private long id;    

@Type(type="yes_no")
@Column(name="ACTIVE")
private Boolean on;

public Boolean getOn() {
    return on;
}

public void setOn(Boolean on) {
    this.on = on;
}

另外,请更改您的查询:

TypedQuery<AnnouncementEntity> query = 
em.createQuery("select p from AnnouncementEntity p where p.on is TRUE", AnnouncementEntity.class);