Hibernate @Filter枚举集合 [英] Hibernate @Filter collection of enums

查看:166
本文介绍了Hibernate @Filter枚举集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to figure out how to apply annotation-based filtering with a parameter list of enums defined as:

@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 看起来像这样:

So my @FilterDef looks like this:

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

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

And when I enable the filter it looks like this:

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

我从休眠状态得到的错误是:

And the Error that I get from hibernate is:

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


$ b的类型不正确$ b

数据在PostgreSQL中,并且定义类型:

The data is in PostgreSQL and the definition of the type:

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

我已经看到很多关于如何对单个枚举进行标准查询和过滤的问题值,但尚未涉及对Enum值的进行过滤。有没有办法显式地转换单个值?

I've seen a lot of SO questions about how to do criteria queries and filters against a single Enum value, but none yet about filtering on a set of Enum values. Is there a way to explicitly cast the individual values?

推荐答案

您通常不必强制转换值,实际上,您只需要以存储它们的形式传递值。

You don't have to "cast" the value in general, in fact you just have to pass the values in the form they are stored.

如果我们假设您的字段仅被注释为 @Enumerated(EnumType .STRING)列为纯varchar字段。
(将Java类型映射到postgres枚举是另一个大话题。)

If we assume your field was only annotated as @Enumerated(EnumType.STRING) the column would be a plain varchar field. (Mapping a java type to a postgres enum is another big topic.)

如果您现在想比较状态的列表在数据库中具有相关字符串值的枚举实例,将其作为字符串集合传递,换句话说,将其称为 toString()方法Java 枚举

If you now want to compare your list of Status enum instances with the related string values in the db, pass it as collection of strings, in other words, call it's toString() method if it's a java enum.

例如这是您的枚举:

public enum EntityStatus {
    A, B, C;
}

这是您的实体:

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

}

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

This could be your code to filter:

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

或者在Java 8之前:

Or in the way before Java 8:

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

因此只过滤值的集合是可能的。

So just filtering for a collection of values is possible.

这篇关于Hibernate @Filter枚举集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆