![](/img/trans.png)
[英]JPA @OneToMany - Set vs List - Not able to delete one child entity from bidirectional association when using Set
[英]JPA bidirectional 1..N association, avoid querying in child to set parent
我正在将Spring Data JPA + Hibernate用于Web应用程序。 对于特定的域模型A,我们在另一个域B中具有一对多关联。这样,A将具有Set getB(),而B将具有A getA()。
查询A图时,我看到休眠状态正在使用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());
}
});
最后是来自日志的休眠查询。 我正在运行一个junit,该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=?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.