JPA Save/Persist Entity Example

Lokesh Gupta

Persisting an entity is the operation of taking a transient entity, or one that does not yet have any persistent representation in the database, and storing its state so that it can be retrieved later. In this example, we have created an entity of type DepartmentEntity and persisted it to database.

@ContextConfiguration(locations = "classpath:application-context-test.xml")
public class TestPersistEntity {
    private EntityManager manager;
	public void testAddDepartment()
		DepartmentEntity department = new DepartmentEntity("Information Technology");
		List<DepartmentEntity> departments = manager.createQuery("Select a From DepartmentEntity a", 
		Assert.assertEquals(department.getName(), departments.get(0).getName());

The line no. 13 in this code segment is simply creating an DepartmentEntity instance that we want to persist.

The next line uses the entity manager to persist the entity. Calling persist() is all that is required to initiate it being persisted in the database. If the entity manager encounters a problem doing this, it will throw an unchecked PersistenceException. When the persist() call completes, ‘department‘ will have become a managed entity within the entity manager’s persistence context.

Above code is built and tested using sourcecode provided for this tutorial.

Happy Learning !!


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode