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
em.createNamedQuery(“selectAuthors”).getResultList();
Session s = (Session) em.getDelegate();
Query q = s.createQuery("SELECT a FROM Author a WHERE id = :id");
q.setParameter("id", 1L);
q.setCacheable(true);
log.info(q.uniqueResult());
@SqlResultSetMapping(
name = "AuthorMapping",
entities = @EntityResult(
entityClass = Author.class,
fields = {
@FieldResult(name = "id", column = "authorId"),
@FieldResult(name = "firstName", column = "firstName"),
@FieldResult(name = "lastName", column = "lastName"),
@FieldResult(name = "version", column = "version")}))
@Entity
@Immutable
public class BookView {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Version
@Column(name = "version")
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Author a = em.createQuery("SELECT a FROM Author a JOIN FETCH a.books WHERE a.id = 1", Author.class).getSingleResult();
em.getTransaction().commit();
em.close();
log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books.");
05:22:13,930 DEBUG [org.hibernate.SQL] –
select authors0_.bookId as bookId1_2_0_,
authors0_.authorId as authorId2_2_0_,
author1_.id as id1_0_1_,
author1_.firstName as firstNam2_0_1_,
author1_.lastName as lastName3_0_1_,
author1_.version as version4_0_1_
from BookAuthor authors0_ inner join Author author1_
on authors0_.authorId=author1_.id
where authors0_.bookId=?
PersonEntity p = em.find(PersonEntity.class, 1L);
log.info("Detach PersonEntity");
em.flush();
em.detach(p);
em.createNativeQuery("UPDATE person p SET firstname = firstname || '-changed'").executeUpdate();
p = em.find(PersonEntity.class, 1L);
Book b = (Book) em.createNativeQuery("SELECT * FROM book b WHERE id = 1", Book.class).getSingleResult();
@Entity
@Table(name = "purchaseOrder")
public class Order implements Serializable {
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
private Set<OrderItem> items = new HashSet<OrderItem>();
...
}
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "author_generator")
@SequenceGenerator(name="author_generator", sequenceName = "author_seq")
@Column(name = "id", updatable = false, nullable = false)
private Long id;
...