有人能解释一下为什么在@ManyToOne 关系上使用@Filter 不起作用吗?
在这里,我有一个非常简单的例子来展示这一点:
我在我的数据库中创建了两个简单的表(foo 和 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;
}
现在当我运行这个查询
@Query("SELECT f FROM Foo f")
public List<Foo> getTest();
它返回 Foo 的全部内容(事件和非事件.....)它看起来过滤器没有被激活,即使我在查询之前运行很艰难
Session session = entityManager.unwrap(Session.class);
session.enableFilter("foo_active")
在日志中,我可以看到:
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'”子句......
有人能帮我解决这个问题吗?
谢谢!
最佳答案
你可以试试这个:代替 @Filter
字段上的 @ManyToOne
,在 class Foo
上添加这个过滤器:
@Filter(name = "foo_active", condition = "bar in (select id from Bar where state = 'active')")
请注意,这可能会导致查询效率低下。
关于在@ManyToOne 上 hibernate @Filter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27180510/