Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Last active September 15, 2015 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thjanssen/0f641e5a56513604be73 to your computer and use it in GitHub Desktop.
Save thjanssen/0f641e5a56513604be73 to your computer and use it in GitHub Desktop.
@Entity
public class Author implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Version
@Column(name = "version")
private int version;
@Column
private String firstName;
@Column
private String lastName;
@ManyToMany(mappedBy="authors")
private Set<Book> books = new HashSet<Book>();
...
}
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Author.class)
public abstract class Author_ {
public static volatile SingularAttribute<Author, String> firstName;
public static volatile SingularAttribute<Author, String> lastName;
public static volatile SetAttribute<Author, Book> books;
public static volatile SingularAttribute<Author, Long> id;
public static volatile SingularAttribute<Author, Integer> version;
}
CriteriaBuilder cb = this.em.getCriteriaBuilder();
// create the query
CriteriaQuery<Author> q = cb.createQuery(Author.class);
// set the root class
Root<Author> a = q.from(Author.class);
// use metadata class to define the where clause
q.where(cb.like(a.get(Author_.firstName), "J%"));
// perform query
this.em.createQuery(q).getResultList();
// create the entity graph
EntityGraph graph = this.em.createEntityGraph(Author.class);
// use metadata class to define the subgraph
Subgraph<Book> bookSubGraph = graph.addSubgraph(Author_.books);
// perform query
List<Author> authors = this.em
.createQuery("SELECT DISTINCT a FROM Author a", Author.class)
.setHint("javax.persistence.fetchgraph", graph).getResultList();
...
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
</dependencies>
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment