Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Last active March 21, 2017 13:14
Show Gist options
  • Save thjanssen/dbc9a110e55418aaa89b to your computer and use it in GitHub Desktop.
Save thjanssen/dbc9a110e55418aaa89b to your computer and use it in GitHub Desktop.
@SqlResultSetMapping(
name = "AuthorValueMapping",
classes = @ConstructorResult(
targetClass = AuthorValue.class,
columns = {
@ColumnResult(name = "id", type = Long.class),
@ColumnResult(name = "firstname"),
@ColumnResult(name = "lastname"),
@ColumnResult(name = "numBooks", type = Long.class)}))
Query q = em.createNamedQuery("selectAuthorValue");
List<AuthorValue> authors = q.getResultList();
for (AuthorValue a : authors) {
System.out.println("Author "
+ a.getFirstName()
+ " "
+ a.getLastName()
+ " wrote "
+ a.getNumBooks()
+ " books.");
}
@NamedNativeQueries({
@NamedNativeQuery(name = "selectAuthorNames", query = "SELECT a.firstname, a.lastname FROM Author a"),
@NamedNativeQuery(name = "selectAuthorEntities", query = "SELECT a.id, a.version, a.firstname, a.lastname FROM Author a", resultClass = Author.class),
@NamedNativeQuery(name = "selectAuthorValue", query = "SELECT a.id, a.firstname, a.lastname, count(b.id) as numBooks FROM Author a JOIN BookAuthor ba on a.id = ba.authorid JOIN Book b ON b.id = ba.bookid GROUP BY a.id", resultSetMapping = "AuthorValueMapping")
})
Query q = em.createNativeQuery("SELECT a.id, a.version, a.firstname, a.lastname FROM Author a", Author.class);
List<Author> authors = q.getResultList();
for (Author a : authors) {
System.out.println("Author "
+ a.getFirstName()
+ " "
+ a.getLastName());
}
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
for (Object[] a : authors) {
System.out.println("Author "
+ a[0]
+ " "
+ a[1]);
}
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a WHERE a.id = :id");
q.setParameter("id", 1);
Object[] author = (Object[]) q.getSingleResult();
System.out.println("Author "
+ author[0]
+ " "
+ author[1]);
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a WHERE a.id = ?");
q.setParameter(1, 1);
Object[] author = (Object[]) q.getSingleResult();
System.out.println("Author "
+ author[0]
+ " "
+ author[1]);
Query q = em.createNativeQuery("SELECT a.id, a.firstname, a.lastname, count(b.id) as numBooks FROM Author a JOIN BookAuthor ba on a.id = ba.authorid JOIN Book b ON b.id = ba.bookid GROUP BY a.id", "AuthorValueMapping");
List<AuthorValue> authors = q.getResultList();
for (AuthorValue a : authors) {
System.out.println("Author "
+ a.getFirstName()
+ " "
+ a.getLastName()
+ " wrote "
+ a.getNumBooks()
+ " books.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment