Search in sources :

Example 51 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.

the class HelloWorldJPA method storeLoadMessage.

@Test
public void storeLoadMessage() throws Exception {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");
    try {
        {
            /* 
                    Get access to the standard transaction API <code>UserTransaction</code> and
                    begin a transaction on this thread of execution.
                 */
            UserTransaction tx = TM.getUserTransaction();
            tx.begin();
            /* 
                    Begin a new session with the database by creating an <code>EntityManager</code>, this
                    is your context for all persistence operations.
                 */
            EntityManager em = emf.createEntityManager();
            /* 
                    Create a new instance of the mapped domain model class <code>Message</code> and
                    set its <code>text</code> property.
                 */
            Message message = new Message();
            message.setText("Hello World!");
            /* 
                    Enlist the transient instance with your persistence context, you make it persistent.
                    Hibernate now knows that you wish to store that data, it doesn't necessarily call the
                    database immediately, however.
                 */
            em.persist(message);
            /* 
                    Commit the transaction, Hibernate now automatically checks the persistence context and
                    executes the necessary SQL <code>INSERT</code> statement.
                 */
            tx.commit();
            // INSERT into MESSAGE (ID, TEXT) values (1, 'Hello World!')
            /* 
                    If you create an <code>EntityManager</code>, you must close it.
                 */
            em.close();
        }
        {
            /* 
                    Every interaction with your database should occur within explicit transaction boundaries,
                    even if you are only reading data.
                 */
            UserTransaction tx = TM.getUserTransaction();
            tx.begin();
            EntityManager em = emf.createEntityManager();
            /* 
                    Execute a query to retrieve all instances of <code>Message</code> from the database.
                 */
            List<Message> messages = em.createQuery("select m from Message m").getResultList();
            // SELECT * from MESSAGE
            assertEquals(messages.size(), 1);
            assertEquals(messages.get(0).getText(), "Hello World!");
            /* 
                    You can change the value of a property, Hibernate will detect this automatically because
                    the loaded <code>Message</code> is still attached to the persistence context it was loaded in.
                 */
            messages.get(0).setText("Take me to your leader!");
            /* 
                    On commit, Hibernate checks the persistence context for dirty state and executes the
                    SQL <code>UPDATE</code> automatically to synchronize the in-memory with the database state.
                 */
            tx.commit();
            // UPDATE MESSAGE set TEXT = 'Take me to your leader!' where ID = 1
            em.close();
        }
    } finally {
        TM.rollback();
        emf.close();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) Message(org.jpwh.model.helloworld.Message) EntityManagerFactory(javax.persistence.EntityManagerFactory) List(java.util.List) Test(org.testng.annotations.Test) TransactionManagerTest(org.jpwh.env.TransactionManagerTest)

Example 52 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.

the class AuditLogging method writeAuditLog.

@Test
public void writeAuditLog() throws Throwable {
    UserTransaction tx = TM.getUserTransaction();
    try {
        Long CURRENT_USER_ID;
        {
            tx.begin();
            EntityManager em = JPA.createEntityManager();
            User currentUser = new User("johndoe");
            em.persist(currentUser);
            tx.commit();
            em.close();
            CURRENT_USER_ID = currentUser.getId();
        }
        EntityManagerFactory emf = JPA.getEntityManagerFactory();
        Map<String, String> properties = new HashMap<String, String>();
        properties.put(org.hibernate.jpa.AvailableSettings.SESSION_INTERCEPTOR, AuditLogInterceptor.class.getName());
        EntityManager em = emf.createEntityManager(properties);
        Session session = em.unwrap(Session.class);
        AuditLogInterceptor interceptor = (AuditLogInterceptor) ((SessionImplementor) session).getInterceptor();
        interceptor.setCurrentSession(session);
        interceptor.setCurrentUserId(CURRENT_USER_ID);
        tx.begin();
        em.joinTransaction();
        Item item = new Item("Foo");
        em.persist(item);
        tx.commit();
        em.clear();
        tx.begin();
        em.joinTransaction();
        List<AuditLogRecord> logs = em.createQuery("select lr from AuditLogRecord lr", AuditLogRecord.class).getResultList();
        assertEquals(logs.size(), 1);
        assertEquals(logs.get(0).getMessage(), "insert");
        assertEquals(logs.get(0).getEntityClass(), Item.class);
        assertEquals(logs.get(0).getEntityId(), item.getId());
        assertEquals(logs.get(0).getUserId(), CURRENT_USER_ID);
        em.createQuery("delete AuditLogRecord").executeUpdate();
        tx.commit();
        em.clear();
        tx.begin();
        em.joinTransaction();
        item = em.find(Item.class, item.getId());
        item.setName("Bar");
        tx.commit();
        em.clear();
        tx.begin();
        em.joinTransaction();
        logs = em.createQuery("select lr from AuditLogRecord lr", AuditLogRecord.class).getResultList();
        assertEquals(logs.size(), 1);
        assertEquals(logs.get(0).getMessage(), "update");
        assertEquals(logs.get(0).getEntityClass(), Item.class);
        assertEquals(logs.get(0).getEntityId(), item.getId());
        assertEquals(logs.get(0).getUserId(), CURRENT_USER_ID);
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) User(org.jpwh.model.filtering.interceptor.User) HashMap(java.util.HashMap) Item(org.jpwh.model.filtering.interceptor.Item) AuditLogRecord(org.jpwh.model.filtering.interceptor.AuditLogRecord) EntityManager(javax.persistence.EntityManager) EntityManagerFactory(javax.persistence.EntityManagerFactory) Session(org.hibernate.Session) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 53 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.

the class AccessJPAMetamodel method accessDynamicMetamodel.

@Test
public void accessDynamicMetamodel() throws Exception {
    EntityManagerFactory entityManagerFactory = JPA.getEntityManagerFactory();
    Metamodel mm = entityManagerFactory.getMetamodel();
    Set<ManagedType<?>> managedTypes = mm.getManagedTypes();
    assertEquals(managedTypes.size(), 1);
    ManagedType itemType = managedTypes.iterator().next();
    assertEquals(itemType.getPersistenceType(), Type.PersistenceType.ENTITY);
    SingularAttribute nameAttribute = itemType.getSingularAttribute("name");
    assertEquals(nameAttribute.getJavaType(), String.class);
    assertEquals(nameAttribute.getPersistentAttributeType(), Attribute.PersistentAttributeType.BASIC);
    assertFalse(// NOT NULL
    nameAttribute.isOptional());
    SingularAttribute auctionEndAttribute = itemType.getSingularAttribute("auctionEnd");
    assertEquals(auctionEndAttribute.getJavaType(), Date.class);
    assertFalse(auctionEndAttribute.isCollection());
    assertFalse(auctionEndAttribute.isAssociation());
}
Also used : SingularAttribute(javax.persistence.metamodel.SingularAttribute) ManagedType(javax.persistence.metamodel.ManagedType) EntityManagerFactory(javax.persistence.EntityManagerFactory) Metamodel(javax.persistence.metamodel.Metamodel) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 54 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.

the class JpaApplication method main.

public static void main(String[] args) {
    EntityManagerFactory factory = null;
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        factory = Persistence.createEntityManagerFactory("infinite-finances");
        em = factory.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // select t from transaction t
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Transaction> criteriaQuery = cb.createQuery(Transaction.class);
        Root<Transaction> root = criteriaQuery.from(Transaction.class);
        criteriaQuery.select(root);
        TypedQuery<Transaction> query = em.createQuery(criteriaQuery);
        List<Transaction> transactions = query.getResultList();
        for (Transaction t : transactions) {
            System.out.println(t.getTitle());
        }
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
    } finally {
        em.close();
        factory.close();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) Transaction(com.infiniteskills.data.entities.Transaction) EntityTransaction(javax.persistence.EntityTransaction) EntityManagerFactory(javax.persistence.EntityManagerFactory)

Example 55 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.

the class MySqlApp method main.

public static void main(String[] args) {
    EntityManagerFactory entityManagerFactory = null;
    EntityManager entityManager = null;
    try {
        entityManagerFactory = Persistence.createEntityManagerFactory("test-unit");
        entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        CustomerJpaDao customerDao = new CustomerJpaDao();
        customerDao.setEntityManager(entityManager);
        Customer customer = new Customer();
        customer.setName("Tom");
        customer.setAge(18);
        // CREATE
        Customer createdCustomer = customerDao.save(customer);
        System.out.println(createdCustomer.getId());
        // GET one
        Long customerId = createdCustomer.getId();
        Customer foundCustomer = customerDao.findById(customerId);
        System.out.println(foundCustomer);
        // UPDATE
        foundCustomer.setName("Dick");
        Customer updatedCustomer = customerDao.save(foundCustomer);
        System.out.println(updatedCustomer);
        entityManager.getTransaction().commit();
        // Native Query
        nativeQuery(entityManager);
    } catch (Exception e) {
        entityManager.getTransaction().rollback();
    } finally {
        entityManager.close();
        entityManagerFactory.close();
    }
}
Also used : EntityManager(javax.persistence.EntityManager) Customer(com.company.app.model.Customer) EntityManagerFactory(javax.persistence.EntityManagerFactory) CustomerJpaDao(com.company.app.dao.CustomerJpaDao) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

EntityManagerFactory (javax.persistence.EntityManagerFactory)302 EntityManager (javax.persistence.EntityManager)103 Test (org.junit.Test)90 HashMap (java.util.HashMap)48 EntityTransaction (javax.persistence.EntityTransaction)30 EJBException (javax.ejb.EJBException)22 Map (java.util.Map)17 AssertionFailedError (junit.framework.AssertionFailedError)17 TestFailureException (org.apache.openejb.test.TestFailureException)17 ArrayList (java.util.ArrayList)15 JMSException (javax.jms.JMSException)15 KieSession (org.kie.api.runtime.KieSession)14 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)14 Properties (java.util.Properties)13 InitialContext (javax.naming.InitialContext)13 List (java.util.List)12 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)12 RemoteException (java.rmi.RemoteException)11 Query (javax.persistence.Query)11 PrintWriter (java.io.PrintWriter)10