0

我有实体:

@Entity(name = "sent_message")
public class SentMessage extends AbstractEntity {
    @ManyToOne(fetch = FetchType.LAZY)
    private TargetGroup targetGroup;
    @ManyToOne(fetch = FetchType.LAZY)
    private Customer customer;
    @ManyToOne(fetch = FetchType.LAZY)
    private MessageTemplate template;
    private Date sentDate;
    getter.setter...
}

@Entity(name = "target_group")
public class TargetGroup extends AbstractEntity {
    private String name;
    private String description;
    @ManyToMany(fetch = FetchType.LAZY)
    private List<Customer> customers = new ArrayList<>();
    getter.setter...
}

@Entity(name = "customer")
public class Customer extends AbstractEntity {
    private String name;
    private String email;
    private String mobile;
    @ManyToMany(mappedBy="customers", fetch = FetchType.LAZY)
    private List<TargetGroup> targetGroups = new ArrayList<>();
    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
    private List<SentMessage> sentMessages = new ArrayList<>();
    getter.setter...
}

@Entity(name = "message_template")
public class MessageTemplate extends AbstractEntity {
    private String subject;
    private String text;
    @OneToMany(mappedBy = "template", fetch = FetchType.LAZY)
    private List<SentMessage> sentMessages;
    getter.setter...
}

我希望 TargetGroup、Customer、MessageTemplate 成为查询的结果。我的选择:

SELECT msg FROM SentMessage msg JOIN msg.targetGroup tg, msg.customer cust, msg.template temp WHERE ....

这是正确的,或者我应该怎么写?我想要所有实体的所有参数。谢谢!

编辑:我想按 TargetGroup 的名称、客户的名称和其他名称进行搜索,我应该如何在 WHERE 中写入?

4

1 回答 1

1

select您必须在查询的子句中列出您想要的结果:

SELECT msg.targetGroup, msg.customer, msg.template FROM SentMessage msg 

你会得到一个Object[]包含数据的。

如果由于延迟提取而遇到问题,可以添加 fetch 连接来检索相关实体:

SELECT msg.targetGroup, msg.customer, msg.template FROM SentMessage msg join fetch msg.targetGroup tg join fetch  msg.customer cust join fetch msg.template temp

编辑您的评论表明您还需要结果中的“父”消息。在这种情况下,创建投影查询(列出 select 子句中的所有属性)是没有意义的。只需获取父消息并调用常规 getter 来访问Customer,TargetGroup和其他关联。如果出现延迟获取问题,请使用获取连接。

SELECT msg FROM SentMessage msg 

或者

SELECT msg FROM SentMessage msg join fetch msg.targetGroup tg join fetch  msg.customer cust join fetch msg.template temp

编辑 2要为查询添加约束,您可以添加where引用任何 id 变量的常规子句:

... join fetch  msg.customer cust where cust.name = :cust_name... 

然而 fetch join 与 where 子句的行为有点出乎意料 - fetch 也受到该where子句的限制。请参阅此线程以供参考

于 2013-10-22T08:08:28.510 回答