Overview
In this guide, you can learn how to use the MongoDB Extension for Hibernate ORM to run create, read, update, and delete (CRUD) operations on your MongoDB collections.
Sample Data
The examples in this guide use the Movie entity, which represents
the sample_mflix.movies collection from the Atlas sample datasets.
The Movie entity has the following definition:
import com.mongodb.hibernate.annotations.ObjectIdGenerator; import org.bson.types.ObjectId; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; public class Movie { private ObjectId id; private String title; private String plot; private int year; private String[] cast; public Movie(String title, String plot, int year, String[] cast) { this.title = title; this.plot = plot; this.year = year; this.cast = cast; } public Movie() { } public ObjectId getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPlot() { return plot; } public void setPlot(String plot) { this.plot = plot; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String[] getCast() { return cast; } public void setCast(String[] cast) { this.cast = cast; } }
To learn how to create a Java application that uses the MongoDB Extension for Hibernate ORM to interact with this MongoDB sample collection, see the Get Started tutorial.
Important
Persistence Contexts
To enable Hibernate ORM to interact with the database, you must run
operations inside a persistence context by using a Hibernate
Session or a Jakarta Persistence EntityManager. You also must run write operations inside a transaction to modify MongoDB
data and maintain data integrity.
Before running the examples in this guide, ensure that you add persistence context and transaction management code to your application that resembles the following code:
var sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); // ... Perform CRUD operations here tx.commit(); session.close(); sf.close();
To use a session, you must create a HibernateUtil.java file that
configures a SessionFactory. To learn more, see the Configure your Application
step of the Get Started tutorial.
// Replace <persistence unit> with the name of your persistence unit in the persistence.xml file EntityManagerFactory emf = Persistence.createEntityManagerFactory("<persistence unit>"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); // ... Perform CRUD operations here entityManager.getTransaction().commit(); entityManager.close(); emf.close;
To use an EntityManager, you must create a persistence.xml file that declares a persistence
unit. To learn more, see the Tutorial using JPA-standard APIs
in the Hibernate ORM documentation.
Insert Documents
To insert a document into a collection, create a new entity instance. Then, you can pass this instance as an argument to the following methods to save it to your MongoDB collection as a document:
org.hibernate.Session.persist(): Use the Hibernate API to apply your changes to the databasejakarta.persistence.EntityManager.persist(): Use the Jakarta Persistence API to apply your changes to the database
Tip
To learn more about creating entity instances and persisting them to your database, see Making entities persistent in the Hibernate ORM user guide.
Example
The following example creates a new Movie entity instance and uses
the persist() method to insert a corresponding document into
the sample_mflix.movies collection:
var myMovie = new Movie(); myMovie.setTitle("Knives Out"); myMovie.setYear(2019); myMovie.setCast(new String[]{"Ana de Armas", "Daniel Craig", "Chris Evans"}); myMovie.setPlot("Detective Benoit Blanc investigates the mysterious death of crime novelist Harlan Thrombey, " + "unraveling lies as every Thrombey family member becomes a suspect."); session.persist(myMovie);
var myMovie = new Movie(); myMovie.setTitle("Knives Out"); myMovie.setYear(2019); myMovie.setCast(new String[]{"Ana de Armas", "Daniel Craig", "Chris Evans"}); myMovie.setPlot("Detective Benoit Blanc investigates the mysterious death of crime novelist Harlan Thrombey, " + "unraveling lies as every Thrombey family member becomes a suspect."); entityManager.persist(myMovie);
Read Documents
To retrieve documents from your collection, pass your query criteria
to the createQuery() method. The following APIs both provide the createQuery()
method:
Hibernate's
SessionAPI: Use Hibernate Query Language (HQL) syntax to define your queriesJakarta Persistence's
EntityManagerAPI: Use Jakarta Persistence Query Language (JPQL) syntax, a subset of HQL, to define your queries
Tip
To learn more about retrieving data by using HQL and JPQL syntax, see Select statements in the Hibernate ORM query guide.
Note
This section describes how to read documents by using HQL and JPQL, but you can also use the criteria builder or native queries to retrieve data. To learn more, see the following guides:
Return One Document Example
To retrieve only one document that matches your query criteria, chain the
getSingleResult() method to the createQuery() method. The following
example retrieves one document that has a title value of "Boyhood"
from the sample_mflix.movies collection:
var singleResult = session.createQuery("from Movie where title = :t", Movie.class) .setParameter("t", "Boyhood") .getSingleResult(); System.out.println("Title: " + singleResult.getTitle() + ", Year: " + singleResult.getYear());
Title: Boyhood, Year: 2014
var singleResult = entityManager.createQuery("select m from Movie m where m.title = :t", Movie.class) .setParameter("t", "Boyhood") .getSingleResult(); System.out.println("Title: " + singleResult.getTitle() + ", Year: " + singleResult.getYear());
Title: Boyhood, Year: 2014
Tip
Query Syntax
To learn more about HQL and JPQL syntax, see A Guide to Hibernate Query Language in the Hibernate ORM documentation.
Return Multiple Documents Example
The following example calls the createQuery() method on a session
to retrieve documents from the sample_mflix.movies collection. The code
uses HQL and JPQL to return documents that have a year value of 1920 and prints
their title values:
var results = session.createQuery("from Movie where year = :y", Movie.class) .setParameter("y", 1920) .getResultList(); results.forEach(movie -> System.out.println(movie.getTitle()));
High and Dizzy One Week The Saphead The Daughter of Dawn
var results = entityManager.createQuery("select m from Movie m where m.year = :y", Movie.class) .setParameter("y", 1920) .getResultList(); results.forEach(movie -> System.out.println(movie.getTitle()));
High and Dizzy One Week The Saphead The Daughter of Dawn
Modify Documents
You can perform the following operations to modify documents in a collection:
Update one document: Call your entity's setter methods to change field values of one entity instance, and then use a session or entity manager to persist your changes.
Update multiple documents: Pass an update statement to the
createQuery()orcreateMutationQuery()methods on a session or entity manager. Then, call theexecuteUpdate()method to apply your changes to the database.
Tip
To learn more about modifying data by using Hibernate ORM, see the following resources:
Modifying managed/persistent state in the Hibernate ORM user guide
Update statements in the Hibernate ORM query guide
Update One Example
The following example retrieves a document by its ObjectId value.
Then, the example calls the Movie entity's setTitle()
method to update the document's title value to "Jurassic Park I":
// Your ObjectId value might differ Movie movieById = session.get(Movie.class, new ObjectId("573a1399f29313caabcedc5d")); movieById.setTitle("Jurassic Park I"); session.persist(movieById);
// Your ObjectId value might differ Movie movieById = entityManager.find(Movie.class, new ObjectId("573a1399f29313caabcedc5d")); movieById.setTitle("Jurassic Park I"); entityManager.persist(movieById);
Update Multiple Example
The following example updates the title value of matching documents
from "The Three Stooges" to "The 3 Stooges". Then, the example
calls the executeUpdate() method to apply the changes
to the database:
var updateResult = session.createMutationQuery( "update Movie set title = :new where title = :old") .setParameter("new", "The 3 Stooges") .setParameter("old", "The Three Stooges") .executeUpdate(); System.out.println("Number of movies updated: " + updateResult);
Number of movies updated: 2
var updateResult = entityManager.createQuery( "update Movie m set m.title = :new where m.title = :old") .setParameter("new", "The 3 Stooges") .setParameter("old", "The Three Stooges") .executeUpdate(); System.out.println("Number of movies updated: " + updateResult);
Number of movies updated: 2
Delete Documents
You can perform the following operations to delete documents from a collection:
Delete one document: Call the
remove()method on a session or entity manager, passing the entity instance that you want to delete as an argument.Delete multiple documents: Pass a delete statement to the
createQuery()orcreateMutationQuery()methods on a session or entity manager. Then, call theexecuteUpdate()method to apply your changes to the database.
Tip
To learn more about deleting data by using Hibernate ORM, see the following resources:
Deleting entities in the Hibernate ORM user guide
Delete statements in the Hibernate ORM query guide
Delete One Example
The following example retrieves a document by its ObjectId value.
Then, the example calls the remove() method on a session
to delete the corresponding document from the sample_mflix.movies
collection:
// Your ObjectId value might differ Movie movieToDelete = session.get(Movie.class, new ObjectId("573a1399f29313caabcedc5d")); session.remove(movieToDelete);
// Your ObjectId value might differ Movie movieToDelete = entityManager.find(Movie.class, new ObjectId("573a1399f29313caabcedc5d")); entityManager.remove(movieToDelete);
Delete Multiple Example
The following example deletes all documents that have a year value of 1920
from the sample_mflix.movies collection. The example passes a
delete statement to the createMutationQuery() method, and then calls the
executeUpdate() method to apply the changes to the database:
var deleteResult = session.createMutationQuery( "delete Movie where year = :y") .setParameter("y", 1920) .executeUpdate(); System.out.println("Number of movies deleted: " + deleteResult);
Number of movies deleted: 4
var deleteResult = entityManager.createQuery( "delete Movie m where m.year = :y") .setParameter("y", 1920) .executeUpdate(); System.out.println("Number of movies deleted: " + deleteResult);
Number of movies deleted: 4
Additional Information
To learn more about performing CRUD operations by using the Hibernate ORM, see the following resources:
Persistence Context in the Hibernate ORM user guide
Statement types in the Hibernate ORM query guide
To view more create, read, update, and delete examples, see the following sections of the Get Started tutorial:
To learn more about using the Hibernate ORM extension to run queries, see the following guides: