title: Hibernate annotation to a transient collection field
body: <p>I would like a collection field to use a query, but I cannot find a way to do it. There is a <code>@Formula</code> annotation, but that doesn't work with collections.
  You might ask why I just don't use <code>@ManyToMany</code> or similar annotation. The thing is, I have a table (say, called Relationships) with columns similar to this:</p>
  
  <p><code>ID | ChildType | ChildID | ParentType | ParentID |</code></p>
  
  <p>Now, the ChildType and ParentType can be one of many classes in my application, therefore I cannot (I don't want to) use <code>@ManyToMany</code> mapping, since it will create another table for each class. What I would like is, to have a collection field called relationships in, say, class A, that would select all rows (relationships) from Relationship table, <code>where ChildID = A.id and ChildType = 'A'</code>. Is that possible?</p>
  
  <p><strong>Update:</strong> Looks like I haven't made myself clear enough. Ok, say, I have a class Relationship where <code>ParentType</code> and <code>ChildType</code> are just class names of parent and child as a String:</p>
  
  <pre><code>@Entity
  public class Relationship {
      @Id
      @GeneratedValue
      private Long id;
      @Enumerated(EnumType.STRING)
      private ParentType parentType;
      private Long parentId;
      @Enumerated(EnumType.STRING)
      private ParentType childType;
      private Long childId;
  }
  </code></pre>
  
  <p>Then I have all kinds of classes that have a field <code>relationships</code>, say:</p>
  
  <pre><code>@Entity
  public class A {
      @Id
      @GeneratedValue
      private Long id;
      private Set&lt;Relationship&gt; relationships = new HashSet&lt;Relationship&gt;();
  }
  
  @Entity
  public class B {
      @Id
      @GeneratedValue
      private Long id;
      private Set&lt;Relationship&gt; relationships = new HashSet&lt;Relationship&gt;();
  }
  
  @Entity
  public class C {
      @Id
      @GeneratedValue
      private Long id;
      private Set&lt;Relationship&gt; relationships = new HashSet&lt;Relationship&gt;();
  }
  </code></pre>
  
  <p>Now I want Hibernate to query the <code>Relationships</code> table to find the relationships for each class, <code>A</code>, <code>B</code>, and <code>C</code> whenever I get an instance bean of corresponding class.
  Something like this:</p>
  
  <pre><code>@Query("(select relationship from Relationship relationship where relationship.childId = id and relationship.childType = 'A')")
  private Set&lt;Relationship&gt; relationships = new ArrayList&lt;Relationship&gt;();
  </code></pre>