Hibernate @Filter枚举集

时间:2015-07-23 20:46:46

标签: java hibernate postgresql enums

我需要弄清楚如何将基于注释的过滤应用于定义为的枚举参数列表:

@Column(name = "target_status")
@Enumerated(EnumType.STRING)
@Type(type="PGEnumConverter", parameters = {
    @Parameter(name = "enumClassName",
               value = "com.company.model.campaign.CampaignTarget$Status")
})
private Status targetStatus;

所以我的@FilterDef看起来像这样:

    @FilterDef(name="filterCampaignTargetByStatuses",
               defaultCondition="target_status in (:statuses)",
               parameters = @ParamDef(name = "statuses", type = "string"))

当我启用过滤器时,它看起来像这样:

    session.enableFilter("filterCampaignTargetByStatuses").
    setParameterList("statuses", statuses);

我从休眠中得到的错误是:

 org.hibernate.HibernateException: Incorrect type for parameter [statuses]

数据在PostgreSQL中以及类型的定义:

CREATE TYPE statuscmp AS ENUM ('ACTIVE','INACTIVE','PAUSED','DRAFT','SCHEDULED','ENDED','ARCHIVED');

我已经看到很多关于如何针对单个Enum值执行条件查询和过滤的SO问题,但还没有关于过滤Enum值的的问题。有没有办法明确地转换个别值?

1 个答案:

答案 0 :(得分:0)

您不必一般“强制转换”该值,实际上您只需要以它们存储的形式传递值。

如果我们假设您的字段仅注释为@Enumerated(EnumType.STRING),则该列将是纯varchar字段。 (将java类型映射到postgres枚举是另一个重要主题。)

如果您现在想要将Status枚举实例的列表与数据库中的相关字符串值进行比较,请将其作为字符串集合传递,换句话说,如果是toString()方法,请将其称为enum方法java public enum EntityStatus { A, B, C; }

E.g。这是你的枚举:

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;

@Entity
@FilterDef(name = "byMultipleStates", defaultCondition = "status in (:states)", parameters = @ParamDef(name = "states", type = "string"))
@Filter(name = "byMultipleStates", condition = "status in (:states)")
public class StatusEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Enumerated(EnumType.STRING)
    private EntityStatus status;

    public long getId() {
        return id;
    }

    public EntityStatus getStatus() {
        return status;
    }

    public void setStatus(EntityStatus status) {
        this.status = status;
    }

}

这是你的实体:

public List<StatusEntity> filterByStates(final Set<EntityStatus> states) {
    final Session hibernateSession = entityManager.unwrap(Session.class);
    hibernateSession.enableFilter("byMultipleStates").setParameterList("states",
            states.stream().map(state -> state.toString()).collect(Collectors.toList()));
    final Query query = hibernateSession.createQuery("SELECT e FROM StatusEntity e");

    return query.list();
}

这可能是您要过滤的代码:

public List<StatusEntity> filterByStates(final Set<EntityStatus> states) {
    final Set<String> statesAsString = new HashSet<>();
    for (final EntityStatus state : states) {
        statesAsString.add(state.toString());
    }

    final Session hibernateSession = entityManager.unwrap(Session.class);
    hibernateSession.enableFilter("byMultipleStates").setParameterList("states", statesAsString);
    final Query query = hibernateSession.createQuery("SELECT e FROM StatusEntity e");

    return query.list();
}

或者在Java 8之前的方式:

app.get('*', function (request, response, next) {
   let app = request.cookies.app;
   if (app) {
     response.sendFile(path.resolve(__dirname, 'app.html')) 
   } else {
     response.sendFile(path.resolve(__dirname, 'app2.html')) 
   }
});

因此,只需过滤一组值即可。