1

A small briefing on what I am trying to do.

I have three tables Content(contentId, body, timeofcreation), ContentAttachmentMap(contentId, attachmentId) and Attachment(attachmentId, resourceLocation).

The reason I adopted to create the mapping table because in future application the attachment can also be shared with different content.

Now I am using HQL to get data. My objectives is as follows:

  1. Get All contents with/without Attachments

I have seen some examples in the internet like you can create an objective specific class (not POJO) and put the attribute name from the select statement within its constructor and the List of that Class object is returned.

For e.g. the HQL will be SELECT new com.mydomain.myclass(cont.id, cont.body) ..... and so on.

In my case I am looking for the following SELECT new com.mydomain.contentClass(cont.id, cont.body, List<Attachment>) FROM ...`. Yes, I want to have the resultList contain contentid, contentbody and List of its Attachments as a single result List item. If there are no attachments then it will return (cont.id, contentbody, null).

Is this possible? Also tell me how to write the SQL statements.

Thanks in advance.

4

1 回答 1

2

我觉得您以一种根本错误的方式使用 Hibernate。您应该使用 Hibernate 来查看您的域实体,而不是将其用作暴露基础表。

对于所有这些,您不需要拥有那个contentClass特殊的值对象。只需选择 Content 实体即可满足您的需求。

我认为有实际的例子会更容易。

在您的应用程序中,您不会将其视为“3 个表”,您应该将其视为 2 个实体,如下所示:

@Entity
public class Content {
  @Id
  Long id;

  @Column(...)
  String content;

  @ManyToMany
  @JoinTable(name="ContentAttachmentMap")
  List<Attachment> attachments;
}

@Entity
public class Attachment {
  @Id
  Long id;

  @Column(...)
  String resourceLocation
}

而且,您正在寻找的结果只是 HQL 之类的结果

from Content where attachments IS EMPTY

我相信您也可以加入 fetch 以节省数据库访问权限:

from Content c left join fetch c.attachments where c.attachments IS EMPTY

于 2013-01-22T07:08:10.530 回答