Skip to content

Instantly share code, notes, and snippets.

View thjanssen's full-sized avatar
🎓
Creating the best Java persistence courses for the @Persistence-Hub

Thorben Janssen thjanssen

🎓
Creating the best Java persistence courses for the @Persistence-Hub
View GitHub Profile
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = “id”, updatable = false, nullable = false)
private Long id;
@Column
private String firstName;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = “id”, updatable = false, nullable = false)
private Long id;
@NaturalId
private String isbn;
HashMap<String, Object> hints = new HashMap<>();
hints.put("javax.persistence.query.timeout", 1000);
em.find(Author.class, 1L, hints);
@Entity
@NamedQuery(name = “Hibernate5Book.findByTitle”, query = “SELECT b FROM Hibernate5Book b WHERE b.title = :title”)
@NamedQuery(name = “Hibernate5Book.findByPublishingDate”, query = “SELECT b FROM Hibernate5Book b WHERE b.publishingDate = :publishingDate”)
public class Hibernate5Book implements Serializable {
}
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = “id”, updatable = false, nullable = false)
private Long id;
@Column
private LocalDate dateOfBirth;
@Entity
public class Book {
...
@Column
private LocalDate publishingDate;
...
// Prepare query
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = cb.createTupleQuery();
Root<Author> author = q.from(Author.class);
// Select multiple scalar values
q.multiselect(author.get(Author_.firstName).alias("firstName"), author.get(Author_.lastName).alias("lastName"));
List<Tuple> authorNames = em.createQuery(q).getResultList();
List<Book> books = session.createQuery("SELECT b FROM Book b", Book.class).list();
books.stream()
.map(b -> b.getTitle() + " was published on " + b.getPublishingDate())
.forEach(m -> log.info(m));
List<Object[]> result = em.createQuery(
"SELECT a, p FROM Author a JOIN a.publications p
WHERE treat(p AS Book).title LIKE '%Java%'")
.getResultList();
Session session = em.unwrap(Session.class);