在@ManyToOne上休眠@Filter [英] Hibernate @Filter on @ManyToOne

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

问题描述

能否请您解释一下为什么对@ManyToOne关系使用@Filter无效? 在这里,我有一个非常简单的示例显示此内容:

Could some please explain me why Having a @Filter on a @ManyToOne relation does not work? Here i have a really simple example showing this:

我已经在数据库中创建了两个简单的表(foo和bar)

I have created two simple table in my database (foo and bar)

Foo: id/id_bar
bar: id/name/state (state can be active or inactive)

和我的实体:

@Entity
@FilterDef(name = "foo_active")
@Table(name = "foo")
public class Foo extends AbstractTimestampEntity implements Serializable {


    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "id")
    private Integer id;

    @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
    @JoinColumn(name = "bar")
    @Filter(name = "foo_active", condition = "state='active'")
    private Bar bar;
}

@Entity
@Table(name = "foo")
public class Bar extends AbstractTimestampEntity implements Serializable {


    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

    @Column(name = "state")
    private String state;
}

现在,当我运行此查询时

Now when I run this query

@Query("SELECT f FROM Foo f")
public List<Foo> getTest();

它返回Foo的全部内容(活动的和不活动的...),即使我在查询之前就很难运行,看起来过滤器也没有被激活

it returns the full content of Foo (active as well as inactive.....) it looks like the filter is not activated even tough i run just before the query

Session session = entityManager.unwrap(Session.class);
session.enableFilter("foo_active")

在日志中,我可以看到:

In the log I can see this:

0:47:33.878 [Test worker] DEBUG o.h.h.i.ast.QueryTranslatorImpl - HQL: SELECT f FROM pl.jcommerce.ocean.services.model.Foo f
00:47:33.878 [Test worker] DEBUG o.h.h.i.ast.QueryTranslatorImpl - S**QL: select foo0_.id as id1_5_, foo0_.created as created2_5_, foo0_.updated as updated3_5_, foo0_.bar as bar6_5_ from foo foo0_**

如您所见,这里有"WHERE bar.state ='active'"子句....

As you see, there is "WHERE bar.state='active'" clause....

这可以帮助我吗?

谢谢!

推荐答案

最近与@ManyToOne一起使用时,我遇到了与@Filter相同的问题.诀窍是在目标实体而不是关联上使用@Filter.

I faced the same issue with @Filter when using along with @ManyToOne recently. The trick is to use @Filter on the target entity not on the association.

@Entity
@Table(name = "foo")
@Filter(name = "foo_active", condition = "state='active'")
public class Bar

Foo类中的关联应类似于:

and the association in Foo class should be like:

@ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@JoinColumn(name = "bar")
private Bar bar;

希望这会有所帮助!

这篇关于在@ManyToOne上休眠@Filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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