JPA双向1..N关联,避免在子进程中查询设置父对象

时间:2015-10-14 10:01:45

标签: java spring hibernate jpa

我正在使用Spring Data JPA + Hibernate作为webapp。对于特定的域模型A,我们在另一个域B中具有1对多的关联。这样A将具有Set getB()并且B将具有A getA()。

在查询A图时,我看到hibernate正在使用1 + n个查询。用于获取A图的单个外连接查询,然后'n'查询在每个B中设置A.

我在这里错过任何模式吗?由于所有孩子都拥有相同的父母,因此不可能以某种方式避免这些'n'查询?





    @MappedSuperclass
    @Data
    public abstract class Batch implements Serializable {

      private static final long serialVersionUID = 1L;

      @OneToOne(fetch = FetchType.EAGER)
      @JoinColumn(name = "batch_id", referencedColumnName = "batch_id")
      protected BatchID batchId;

    }


    /*
    //The parent class in a simplified form
    */
    @Entity
    @Table(name = "DRYRUN")
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class DryrunBatch extends Batch {

      /**
       * 
       */
      private static final long serialVersionUID = -1596595930859735318L;
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Getter@Setter
      protected Long id;

      public DryrunTNStatus newTNStatus()
      {
        final DryrunTNStatus tn = new DryrunTNStatus();
        tn.setBatch(this);
        getTnStatus().add(tn);
        return tn;
      }

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "batch")
      @Getter@Setter
      private Set tnStatus = new HashSet();
    }


    //The child class in a simplified form

    @Entity
    @Table(name = "DRYRUN_TN_STATUS")
    @Data
    public class DryrunTNStatus implements Serializable{

      /**
       * 
       */
      private static final long serialVersionUID = -4388406636444350023L;

      public DryrunTNStatus(String accountNo, String telNo) {
        super();

        this.accountNo = accountNo;
        this.telNo = telNo;
      }

      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "BATCH_ID", referencedColumnName = "BATCH_ID")
      private DryrunBatch batch;

      public DryrunTNStatus()
      {

      }
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      protected Long id;

    }

使用JpaRepository获取对象图的代码。使用Spring JPA支持来强制执行外连接。我更喜欢Hibernate的@Fetch注释。



    DryrunBatch drBatch = drBatchRepo.findOne(new Specification() {

          @Override
          public Predicate toPredicate(Root root, CriteriaQuery query,
              CriteriaBuilder cb) {
            query.distinct(true);
            root.fetch("tnStatus", JoinType.LEFT);
            return cb.equal(root.get("batchId").get("id"),
                batch.getId());

          }
        });

最后来自log的hibernate查询。我正在运行一个junit,它从DB获取一个有10个孩子的父母。



    //this query can fetch data for the complete graph??
    Hibernate: select distinct dryrunbatc0_.id as id1_6_0_, tnstatus1_.id as id1_9_1_[etc..] from dryrun dryrunbatc0_ left outer join dryrun_tn_status tnstatus1_ on dryrunbatc0_.batch_id=tnstatus1_.batch_id where dryrunbatc0_.batch_id=15

    //and then 10 queries like
    Hibernate: select dryrunbatc0_.id as id1_6_3_, [etc..] from dryrun dryrunbatc0_ left outer join batch_id batchid1_ on dryrunbatc0_.batch_id=batchid1_.batch_id inner join users user2_ on dryrunbatc0_.created_by=user2_.login_id left outer join dryrun_tn_status tnstatus3_ on dryrunbatc0_.batch_id=tnstatus3_.batch_id where dryrunbatc0_.batch_id=?

1 个答案:

答案 0 :(得分:0)

你遇到了懒惰加载的着名N + 1问题。没有JPA标准方法来解决这个问题,但是,每个JPA提供程序都提供了打开“批量提取”的方法,它将立即加载所有延迟引用,而不是在单个SQL查询中加载每个。

以下是有关如何在hibernate中启用此功能的信息。

以下是article,其中说明了批量提取的工作原理以及使用eclipselink的示例。

相关问题