有些人可以解释一下为什么在@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'”子句....
有人可以帮我这个吗?
谢谢!
答案 0 :(得分:0)
您可以尝试以下操作:代替@Filter
字段中的@ManyToOne
,在class Foo
上添加此过滤器:
@Filter(name = "foo_active", condition = "bar in (select id from Bar where state = 'active')")
请注意,这可能会导致查询效率低下。
答案 1 :(得分:0)
最近与@Filter
一起使用时,@ManyToOne
遇到了同样的问题。诀窍是在目标实体上使用@Filter
而不在关联上。
@Entity
@Table(name = "foo")
@Filter(name = "foo_active", condition = "state='active'")
public class Bar
并且Foo
类中的关联应该是:
@ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@JoinColumn(name = "bar")
private Bar bar;
希望这有帮助!