首页>Program>source

我在两个表之间具有父/子关系,并且在Java类中具有对应的映射.这些表大致如下所示:

A (ref number, stuff varchar2(4000))
B (a_ref number, other number, foo varchar2(200))

和Java代码:

@Entity
class A {
    @Id
    @Column(name = "REF")
    private int ref;
    @OneToMany
    @JoinColumn(name = "A_REF", referencedName = "REF")
    private Set<B> bs;
}
@Entity
class B {
    @Id
    @Column(name = "A_REF")
    private int aRef;
    @Id
    @Column(name = "OTHER")
    private int other;
}

这很好用,但是我想在从子表中检索的行上添加一个过滤器.生成的查询如下:

select a_ref, other, foo from B where a_ref = ?

我希望它是:

select a_ref, other, foo from B where a_ref = ? and other = 123

附加过滤器将只是列名称和硬编码值.有没有一种使用休眠注释的方法?

我看过 @JoinFormula ,但是我总是必须从父表中引用一个列名(在 name中 JoinFormula的属性)。

事先感谢您提供任何建议。

最新回答
  • 2021-1-11
    1 #

    JPA不支持它,但是如果您将休眠用作JPA提供程序,则可以使用注释 @FilterDef@Filter

    Hibernate Core Reference Documentation

    Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows you to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements. These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be. Filters can be used like database views, but they are parameterized inside the application.

    Exemple

    @Entity
    public class A implements Serializable{
        @Id
        @Column(name = "REF")
        private int ref;
        @OneToMany
        @JoinColumn(name = "A_REF", referencedColumnName = "REF")   
        @Filter(name="test")
        private Set<B> bs;
    }
    @Entity
    @FilterDef(name="test", defaultCondition="other = 123")
    public class B implements Serializable{
        @Id
        @Column(name = "A_REF")
        private int aRef;
        @Id
        @Column(name = "OTHER")
        private int other;
    }
    Session session = entityManager.unwrap(Session.class);
    session.enableFilter("test");
    A a = entityManager.find(A.class, new Integer(0))
    a.getb().size() //Only contains b that are equals to 123
    

  • 2021-1-11
    2 #

    使用JPA 1,您可以使用提供的解决方案,但是将unwrap更改为getDelegate即可

    Session session = (Session)entityManager.getDelegate();
    

    它将起作用。

  • 2021-1-11
    3 #

    如果我正确理解了这个问题,则可以使用javax.persistence注解来解决此问题(我自己在ManyToOne上使用了该方法,并为答案量身定制 从这里开始):

    @JoinColumns({
        @JoinColumn(name = "A_REF", referencedColumnName = "REF"),
        @JoinColumn(name = "B_TABLE_NAME.OTHER", referencedColumnName = "'123'")})
    @OneToMany
    private Set<B> bs;
    

    请注意 single referencedColumnName中的引号,这是您要查找的值。

    更多信息在这里。

  • java:GwT:计时器和计划程序类
  • html:CSS媒体查询问题(滚动条)