HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JPA / Persist Example

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.

Download Sourcecode

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)