title: Subselect to retrieve righthand-side of in-statement using CriteriaBuilder (JPA)
body: <p>I am playing around with JPA and other Java EE 6 stuff, but now I am facing some problems with a types query using the criteria Builder.
  The business case for my poc is a twitter clone, so I have users which has a list of subscribers and subscriptions and I got Tweets. </p>
  
  <pre><code>@Entity
  public class Tweet {
      @Id @GeneratedValue(strategy=GenerationType.AUTO)
      private Long id;
  
      @ManyToOne
      private TwitterUser author;
  
      @ManyToOne
      private TwitterUser receiver;
  
      @Temporal(TemporalType.TIMESTAMP) 
      private Date datetime; 
  
      private String message;
  }
  
  
  @Entity
  public class TwitterUser {
      @Id @GeneratedValue(strategy=GenerationType.AUTO)
      private Long id;
  
      private String username;
  
      private String displayname;
  
      private String password;
  
      private String email;
  
      @Temporal(TemporalType.TIMESTAMP)
      private Date since;
  
      @ManyToMany(cascade=CascadeType.ALL)
      private List&lt;TwitterUser&gt; subscriptions;
  
      @ManyToMany(mappedBy = "subscriptions")
      private List&lt;TwitterUser&gt; subscribers;
  }
  </code></pre>
  
  <p>The datamodel generated by JPA consists of 3 tables: Tweet, TwitterUser and TwitterUser_TwitterUser. Everything's fine so far. Basic queries do work well.</p>
  
  <p>Now I want to select all Tweets for a timeline, what means all tweets of users, who are in the list of subscriptions of the current logged in user. I thought of a solution by using a subselect, so my sql would look like:</p>
  
  <pre><code>select * from TWEET where author_id in (
      select subscriptions_ID from TWITTERUSER_TWITTERUSER where subscribers_ID = ?loggedInUserId);
  </code></pre>
  
  <p>This query works well, but I have no idea how to write it down using the CriteriaBuilder and generics. I don't even get a compilable piece of code that could fail at some other point, because I am not sure what the type of the subquery should be.
  I was searching through lots of examples now, but they are mostly just using raw-types or using the subquery for retrieving the element of the lefthand-side of the in-clause.</p>
  
  <p>Maybe I miss the wood for trees but I am really perplexed here. :(</p>