|
| 1 | +import jakarta.persistence.Entity; |
| 2 | +import jakarta.persistence.EntityManagerFactory; |
| 3 | +import jakarta.persistence.Persistence; |
| 4 | +import jakarta.persistence.PersistenceConfiguration; |
| 5 | +import org.hibernate.jpa.HibernatePersistenceConfiguration; |
| 6 | + |
| 7 | +import java.util.List; |
| 8 | + |
| 9 | +public class Main { |
| 10 | + public static void main(String[] args) { |
| 11 | + |
| 12 | + |
| 13 | + final PersistenceConfiguration cfg = new HibernatePersistenceConfiguration("emf") |
| 14 | + .jdbcUrl("jdbc:mysql://localhost:3306/film_database") |
| 15 | + .jdbcUsername("root") |
| 16 | + .jdbcPassword("root") |
| 17 | + .property("hibernate.hbm2ddl.auto", "update") |
| 18 | + .property("hibernate.show_sql", "true") |
| 19 | + .property("hibernate.format_sql", "true") |
| 20 | + .property("hibernate.highlight_sql", "true") |
| 21 | + .managedClasses(Film.class, Director.class); |
| 22 | + try (EntityManagerFactory emf = cfg.createEntityManagerFactory()) { |
| 23 | + emf.runInTransaction(em -> { |
| 24 | + //If no Films in database, add some |
| 25 | + if (em.createQuery("select count(o) from Film o", Long.class) |
| 26 | + .getSingleResult() == 0) { |
| 27 | + Film film1 = new Film(); |
| 28 | + em.persist(film1); |
| 29 | + em.flush(); |
| 30 | + Film film2 = new Film(); |
| 31 | + em.persist(film2); |
| 32 | + } |
| 33 | + System.out.println("==== Using select query, N + 1 ===="); |
| 34 | + em.createQuery("from Film", Film.class) |
| 35 | + .getResultList().forEach(System.out::println); |
| 36 | + |
| 37 | + }); |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + } |
| 42 | +} |
0 commit comments