Search in sources :

Example 1 with PersistenceUnitUtil

use of jakarta.persistence.PersistenceUnitUtil in project hibernate-orm by hibernate.

the class PersistenceContextTest method test.

@Test
public void test() {
    doInJPA(this::entityManagerFactory, entityManager -> {
        // tag::pc-unwrap-example[]
        Session session = entityManager.unwrap(Session.class);
        SessionImplementor sessionImplementor = entityManager.unwrap(SessionImplementor.class);
        SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class);
    // end::pc-unwrap-example[]
    });
    Long _personId = doInJPA(this::entityManagerFactory, entityManager -> {
        entityManager.createQuery("delete from Book").executeUpdate();
        entityManager.createQuery("delete from Person").executeUpdate();
        // tag::pc-persist-jpa-example[]
        Person person = new Person();
        person.setId(1L);
        person.setName("John Doe");
        entityManager.persist(person);
        // end::pc-persist-jpa-example[]
        // tag::pc-remove-jpa-example[]
        entityManager.remove(person);
        // end::pc-remove-jpa-example[]
        entityManager.persist(person);
        Long personId = person.getId();
        // tag::pc-get-reference-jpa-example[]
        Book book = new Book();
        book.setAuthor(entityManager.getReference(Person.class, personId));
        return personId;
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        // tag::pc-find-jpa-example[]
        Person person = entityManager.find(Person.class, personId);
    // end::pc-find-jpa-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        entityManager.createQuery("delete from Book").executeUpdate();
        entityManager.createQuery("delete from Person").executeUpdate();
        // tag::pc-persist-native-example[]
        Person person = new Person();
        person.setId(1L);
        person.setName("John Doe");
        session.save(person);
        // end::pc-persist-native-example[]
        // tag::pc-remove-native-example[]
        session.delete(person);
        // end::pc-remove-native-example[]
        session.save(person);
        Long personId = person.getId();
        // tag::pc-get-reference-native-example[]
        Book book = new Book();
        book.setId(1L);
        book.setIsbn("123-456-7890");
        entityManager.persist(book);
        book.setAuthor(session.load(Person.class, personId));
    // end::pc-get-reference-native-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-find-native-example[]
        Person person = session.get(Person.class, personId);
    // end::pc-find-native-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-find-by-id-native-example[]
        Person person = session.byId(Person.class).load(personId);
        // end::pc-find-by-id-native-example[]
        // tag::pc-find-optional-by-id-native-example[]
        Optional<Person> optionalPerson = session.byId(Person.class).loadOptional(personId);
        // end::pc-find-optional-by-id-native-example[]
        String isbn = "123-456-7890";
        // tag::pc-find-by-simple-natural-id-example[]
        Book book = session.bySimpleNaturalId(Book.class).getReference(isbn);
        // end::pc-find-by-simple-natural-id-example[]
        assertNotNull(book);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        String isbn = "123-456-7890";
        // tag::pc-find-by-natural-id-example[]
        Book book = session.byNaturalId(Book.class).using("isbn", isbn).load();
        // end::pc-find-by-natural-id-example[]
        assertNotNull(book);
        // tag::pc-find-optional-by-simple-natural-id-example[]
        Optional<Book> optionalBook = session.byNaturalId(Book.class).using("isbn", isbn).loadOptional();
    // end::pc-find-optional-by-simple-natural-id-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        // tag::pc-managed-state-jpa-example[]
        Person person = entityManager.find(Person.class, personId);
        person.setName("John Doe");
        entityManager.flush();
    // end::pc-managed-state-jpa-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        // tag::pc-refresh-jpa-example[]
        Person person = entityManager.find(Person.class, personId);
        entityManager.createQuery("update Person set name = UPPER(name)").executeUpdate();
        entityManager.refresh(person);
        assertEquals("JOHN DOE", person.getName());
    // end::pc-refresh-jpa-example[]
    });
    try {
        doInJPA(this::entityManagerFactory, entityManager -> {
            Long personId = _personId;
            // tag::pc-refresh-child-entity-jpa-example[]
            try {
                Person person = entityManager.find(Person.class, personId);
                Book book = new Book();
                book.setId(100L);
                book.setTitle("Hibernate User Guide");
                book.setAuthor(person);
                person.getBooks().add(book);
                entityManager.refresh(person);
            } catch (EntityNotFoundException expected) {
                log.info("Beware when cascading the refresh associations to transient entities!");
            }
        // end::pc-refresh-child-entity-jpa-example[]
        });
    } catch (Exception expected) {
    }
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-managed-state-native-example[]
        Person person = session.byId(Person.class).load(personId);
        person.setName("John Doe");
        session.flush();
    // end::pc-managed-state-native-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-refresh-native-example[]
        Person person = session.byId(Person.class).load(personId);
        session.doWork(connection -> {
            try (Statement statement = connection.createStatement()) {
                statement.executeUpdate("UPDATE Person SET name = UPPER(name)");
            }
        });
        session.refresh(person);
        assertEquals("JOHN DOE", person.getName());
    // end::pc-refresh-native-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-detach-reattach-lock-example[]
        Person person = session.byId(Person.class).load(personId);
        // Clear the Session so the person entity becomes detached
        session.clear();
        person.setName("Mr. John Doe");
        session.lock(person, LockMode.NONE);
    // end::pc-detach-reattach-lock-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-detach-reattach-saveOrUpdate-example[]
        Person person = session.byId(Person.class).load(personId);
        // Clear the Session so the person entity becomes detached
        session.clear();
        person.setName("Mr. John Doe");
        session.saveOrUpdate(person);
    // end::pc-detach-reattach-saveOrUpdate-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        Person personDetachedReference = session.byId(Person.class).load(personId);
        // Clear the Session so the person entity becomes detached
        session.clear();
        new MergeVisualizer(session).merge(personDetachedReference);
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        // tag::pc-merge-jpa-example[]
        Person person = entityManager.find(Person.class, personId);
        // Clear the EntityManager so the person entity becomes detached
        entityManager.clear();
        person.setName("Mr. John Doe");
        person = entityManager.merge(person);
        // end::pc-merge-jpa-example[]
        // tag::pc-contains-jpa-example[]
        boolean contained = entityManager.contains(person);
        // end::pc-contains-jpa-example[]
        assertTrue(contained);
        // tag::pc-verify-lazy-jpa-example[]
        PersistenceUnitUtil persistenceUnitUtil = entityManager.getEntityManagerFactory().getPersistenceUnitUtil();
        boolean personInitialized = persistenceUnitUtil.isLoaded(person);
        boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks());
        boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name");
    // end::pc-verify-lazy-jpa-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Long personId = _personId;
        Person person = entityManager.find(Person.class, personId);
        // tag::pc-verify-lazy-jpa-alternative-example[]
        PersistenceUtil persistenceUnitUtil = Persistence.getPersistenceUtil();
        boolean personInitialized = persistenceUnitUtil.isLoaded(person);
        boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks());
        boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name");
    // end::pc-verify-lazy-jpa-alternative-example[]
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Session session = entityManager.unwrap(Session.class);
        Long personId = _personId;
        // tag::pc-merge-native-example[]
        Person person = session.byId(Person.class).load(personId);
        // Clear the Session so the person entity becomes detached
        session.clear();
        person.setName("Mr. John Doe");
        person = (Person) session.merge(person);
        // end::pc-merge-native-example[]
        // tag::pc-contains-native-example[]
        boolean contained = session.contains(person);
        // end::pc-contains-native-example[]
        assertTrue(contained);
        // tag::pc-verify-lazy-native-example[]
        boolean personInitialized = Hibernate.isInitialized(person);
        boolean personBooksInitialized = Hibernate.isInitialized(person.getBooks());
        boolean personNameInitialized = Hibernate.isPropertyInitialized(person, "name");
    // end::pc-verify-lazy-native-example[]
    });
}
Also used : SessionFactory(org.hibernate.SessionFactory) Statement(java.sql.Statement) PersistenceUnitUtil(jakarta.persistence.PersistenceUnitUtil) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) PersistenceUtil(jakarta.persistence.PersistenceUtil) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) Session(org.hibernate.Session) Test(org.junit.Test)

Example 2 with PersistenceUnitUtil

use of jakarta.persistence.PersistenceUnitUtil in project eclipselink by eclipse-ee4j.

the class AdvancedCompositePKJunitTest method testGetIdentifier.

public void testGetIdentifier() {
    EntityManagerFactory emf = getEntityManagerFactory();
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        DepartmentPK pk = new DepartmentPK("DEPT B", "ROLE B", "LOCATION B");
        Department department = new Department();
        department.setName("DEPT B");
        department.setRole("ROLE B");
        department.setLocation("LOCATION B");
        em.persist(department);
        em.flush();
        PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
        assertTrue("Got an incorrect id from persistenceUtil.getIdentifier()", pk.equals(util.getIdentifier(department)));
    } finally {
        rollbackTransaction(em);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) Department(org.eclipse.persistence.testing.models.jpa.advanced.compositepk.Department) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PersistenceUnitUtil(jakarta.persistence.PersistenceUnitUtil) DepartmentPK(org.eclipse.persistence.testing.models.jpa.advanced.compositepk.DepartmentPK)

Example 3 with PersistenceUnitUtil

use of jakarta.persistence.PersistenceUnitUtil in project eclipselink by eclipse-ee4j.

the class EntityGraphTestSuite method testSimpleGraph.

/**
 * Tests a NamedStoredProcedureQuery using a positional parameter returning
 * a single result set.
 */
public void testSimpleGraph() {
    EntityManager em = createEntityManager();
    Employee result = (Employee) em.createQuery("Select e from Employee e join treat(e.projects as LargeProject) p where p.executive is Not Null and e != p.executive").setHint(QueryHints.JPA_FETCH_GRAPH, em.getEntityGraph("Employee")).getResultList().get(0);
    PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil();
    assertFalse("fetchgroup failed to be applied: department is loaded", util.isLoaded(result, "department"));
    assertTrue("Fetch Group was not applied: projects is not loaded", util.isLoaded(result, "projects"));
    for (Project project : result.getProjects()) {
        assertFalse("fetchgroup failed to be applied : teamLeader is loaded", util.isLoaded(project, "teamLeader"));
        assertTrue("fetchgroup failed to be applied: properties is not loaded", util.isLoaded(project, "properties"));
        if (project instanceof LargeProject) {
            assertTrue("Fetch Group was not applied: executive is not loaded", util.isLoaded(project, "executive"));
        }
    }
    closeEntityManager(em);
}
Also used : Project(org.eclipse.persistence.testing.models.jpa21.advanced.Project) LargeProject(org.eclipse.persistence.testing.models.jpa21.advanced.LargeProject) EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa21.advanced.Employee) PersistenceUnitUtil(jakarta.persistence.PersistenceUnitUtil) LargeProject(org.eclipse.persistence.testing.models.jpa21.advanced.LargeProject)

Example 4 with PersistenceUnitUtil

use of jakarta.persistence.PersistenceUnitUtil in project eclipselink by eclipse-ee4j.

the class EntityGraphTestSuite method testLoadGroup.

public void testLoadGroup() {
    EntityManager em = createEntityManager();
    EntityGraph<Employee> employeeGraph = em.createEntityGraph(Employee.class);
    employeeGraph.addAttributeNodes("address");
    Employee result = (Employee) em.createQuery("Select e from Employee e").setMaxResults(1).setHint(QueryHints.JPA_LOAD_GRAPH, employeeGraph).getResultList().get(0);
    PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil();
    assertTrue("LoadGroup was not applied", util.isLoaded(result, "address"));
    assertTrue("LoadGroup was not applied", util.isLoaded(result, "department"));
    assertFalse("LoadGroup was not applied", util.isLoaded(result, "managedEmployees"));
}
Also used : EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa21.advanced.Employee) PersistenceUnitUtil(jakarta.persistence.PersistenceUnitUtil)

Example 5 with PersistenceUnitUtil

use of jakarta.persistence.PersistenceUnitUtil in project eclipselink by eclipse-ee4j.

the class EntityGraphTestSuite method testEmbeddedFetchGroupRefresh.

public void testEmbeddedFetchGroupRefresh() {
    EntityManager em = createEntityManager();
    EntityGraph<Employee> employeeGraph = em.createEntityGraph(Employee.class);
    employeeGraph.addSubgraph("period").addAttributeNodes("startDate");
    Employee result = (Employee) em.createQuery("Select e from Employee e order by e.salary desc").setMaxResults(1).setHint(QueryHints.JPA_FETCH_GRAPH, employeeGraph).getResultList().get(0);
    PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil();
    assertFalse("FetchGroup was not applied", util.isLoaded(result, "department"));
    assertFalse("FetchGroup was not applied", util.isLoaded(result.getPeriod(), "endDate"));
    assertTrue("FetchGroup was not applied", util.isLoaded(result.getPeriod(), "startDate"));
    result = (Employee) em.createQuery("Select e from Employee e order by e.salary desc").setMaxResults(1).setHint(QueryHints.JPA_FETCH_GRAPH, employeeGraph).setHint(QueryHints.REFRESH, true).getResultList().get(0);
}
Also used : EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa21.advanced.Employee) PersistenceUnitUtil(jakarta.persistence.PersistenceUnitUtil)

Aggregations

PersistenceUnitUtil (jakarta.persistence.PersistenceUnitUtil)26 EntityManager (jakarta.persistence.EntityManager)24 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)9 JpaEntityManagerFactory (org.eclipse.persistence.jpa.JpaEntityManagerFactory)7 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)6 Employee (org.eclipse.persistence.testing.models.jpa21.advanced.Employee)4 Employee (org.eclipse.persistence.testing.models.jpa22.advanced.Employee)4 Address (org.eclipse.persistence.testing.models.jpa.advanced.Address)3 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)3 PhoneNumber (org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber)3 Address (org.eclipse.persistence.testing.models.jpa.composite.advanced.member_1.Address)3 Employee (org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.Employee)3 PhoneNumber (org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.PhoneNumber)3 PersistenceWeaved (org.eclipse.persistence.internal.weaving.PersistenceWeaved)2 LargeProject (org.eclipse.persistence.testing.models.jpa21.advanced.LargeProject)2 Project (org.eclipse.persistence.testing.models.jpa21.advanced.Project)2 Runner (org.eclipse.persistence.testing.models.jpa21.advanced.Runner)2 LargeProject (org.eclipse.persistence.testing.models.jpa22.advanced.LargeProject)2 Project (org.eclipse.persistence.testing.models.jpa22.advanced.Project)2 Runner (org.eclipse.persistence.testing.models.jpa22.advanced.Runner)2