JPA Save/Persist Entity Example

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")
@RunWith(SpringJUnit4ClassRunner.class)
public class TestPersistEntity {
	
	@PersistenceContext
    private EntityManager manager;
	
	@Test
	@Transactional
	@Rollback(true)
	public void testAddDepartment()
	{
		DepartmentEntity department = new DepartmentEntity("Information Technology");
		manager.persist(department);
		
		List<DepartmentEntity> departments = manager.createQuery("Select a From DepartmentEntity a", 
																	DepartmentEntity.class).getResultList();
		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 !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

Leave a Comment

About HowToDoInJava

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

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