JPA Persist Example

By | | Updated : 2021-02-22 | Viewed : 199 times

jpa persist example

The current tutorial will show example of persistence() method in JPA with an explanation.

persist() in JPA

In JPA, persist() method will be used for saving the data entity as a record. Please find below-given an example of how to use the persist() method using EntityManager in JPA.

persist() method usage in JPA
entityManager.persist(player);

JPA Persist() Example

persis() method example in JPA
        EntityManager entityManager = JPAUtils.getEntityManagerFactory().createEntityManager();
        EntityTransaction transaction = null;
        try {

            transaction = entityManager.getTransaction();
            transaction.begin();


            Player player = new Player();
            player.setFirstName("Sachin");
            player.setLastName("Tendulkar");
            player.setGame("Cricket");
            player.setAge(47l);
            player.setSalaryIncome(400000L);
            entityManager.persist(player);

            Player player1 = new Player();
            player1.setFirstName("Tom");
            player1.setLastName("Brady");
            player1.setGame("Football");
            player1.setAge(43l);
            player1.setSalaryIncome(400000L);
            entityManager.persist(player1);

            transaction.commit();


        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

Here EntityManager is created using createEntityManager() of EntityManagerFactory class where as Transaction is created getTransaction() of EntityManager class.

We created two entity objects for persisting using EntityManager. After committing the transaction we closed the EntityManager.

Please find the code repository here JPA-Persist-Example-App-With-XML

Leave A Reply