【问题标题】:Default query hibernate OneToMany attribute默认查询休眠 OneToMany 属性
【发布时间】:2016-04-22 18:00:56
【问题描述】:

我正在使用带有 jpa 的 hibernate 4.0,我有一个可以从数据库加载大量数据的一对多关系,我将其设置为延迟加载(如下面的代码)

为了保持历史,当我想删除 B 时,我从不从数据库中删除它,我只是将“关闭”属性设置为 true...

问题是如果我尝试使用以下方式加载所有 A 实例:

session.createCriteria(A.class).list();

对于每个实例,休眠将延迟加载标记为已关闭的 B。我想知道是否有任何注释可以定义为只加载那些“关闭”为假的注释。 避免在我用来加载 A 的每个代码中指定它

 public class A {

        @Id
        private Integer id;

        private String fullName;
        @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = B.class)
        @LazyCollection(LazyCollectionOption.TRUE)
        private List<B> series = new Vector<B>();
}

public class B  {

    @Id
    private Integer id;


    private Boolean closed;
    private Date createdDate;
/**lots of other things**/

}

【问题讨论】:

    标签: java hibernate annotations one-to-many


    【解决方案1】:

    我找到了答案:http://www.mkyong.com/hibernate/hibernate-data-filter-example-xml-and-annotation/

    默认情况下 jpa 不允许这样做,但是 hibernate 为这种情况提供了注释,解决方案是:

    public class A {
    
            @Id
            private Integer id;
    
            private String fullName;
            @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = B.class)
            @LazyCollection(LazyCollectionOption.TRUE)
    @Filter(name="bNotClosed")
            private List<B> series = new Vector<B>();
    }
    
    
    
    
      @FilterDef(name="bNotClosed", defaultCondition="closed= :value", parameters=
    @ParamDef(name="value",type="boolean"))
        public class B  {
    
                @Id
                private Integer id;
    
    
                private Boolean closed;
                private Date createdDate;
            /**lots of other things**/
    
            }
    
    
            session = HibernateUtils.getSessionFactory().openSession();
                        session.enableFilter("bNotClosed").setParameter("value", false);
    

    如果我的参数是一个整数,我可以将它按字面意思放在 defaultCondition="unliked = 123" 中,因此 hibernate 将 false 解释为类属性并会出错,因此我必须在创建会话时定义该值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 2013-07-26
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多