我想使用@Query注释从具有@OneToMany关系的实体创建左连接查询。
父实体是:
@Entity
@Table(name="Registration")
public class Registration {
@Column(nullable = false)
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate effect;
@OneToMany(targetEntity=Payment.class, cascade=CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name="uuid")
private List<Payment> payment;
}
孩子:
@Entity
@Table(name="Payment")
public class Payment {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name="uuid", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
private UUID uuid;
}
对于DAO,我喜欢以下内容:
@Query("SELECT p FROM Registration r JOIN r.payment p WHERE r.effect = :effect")
Iterable<Payment> find(@Param("effect") LocalDate effect);
显然,它的错误是因为生成的查询是:
生成关系表时选择payment1_.uuid作为uuid1_9_,payment1_.amount作为amount2_9_来自注册registrati0_内部加入付款payment1_ on registrati0_.uuid = payment1_.uuid where registrati0_.effect =?
:
对我来说,正确的查询应该是这样的:
从注册r中选择p。*在rp.registration = r.uuid上加入registration_payment rp在p.uuid = rp.payment上加入付款p其中r.effect =&#39; 2015-10-16&#39; < / p>
请问有什么好的查询语法?实际查询返回空数组。
答案 0 :(得分:1)
最后,我找到了解决方案。 您必须使用@JoinTable描述关系表:
@JoinTable(
name="registration_payment",
joinColumns = @JoinColumn(name="registration"),
inverseJoinColumns = @JoinColumn(name = "payment")
)
private List<Payment> payment;
不需要修改@Query:
@Query(&#34; SELECT p FROM Registration r JOIN r.payment p WHERE r.effect =:effect&#34;)
生成的查询是:
选择payment2_.uuid为uuid1_9_,payment2_.amount为amount2_9_ 来自注册registrati0_ reg join_payment payment1_ on registrati0_.uuid = payment1_.registration 内部加入付款payment2_ on payment1_.payment = payment2_.uuid registrati0_.effect =?