MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs 菜单
Docs 主页
/ /

执行 CRUD 操作

在本指南中,您可以学习;了解如何使用MongoDB Extension for Hibernate ORM 在MongoDB集合上运行创建、读取、更新和删除(增删改查 ) 操作。

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 java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "movies")
public class Movie {
@Id
@ObjectIdGenerator
private ObjectId id;
private String title;
private String plot;
private int year;
private List<String> cast;
public Movie(String title, String plot, int year, List<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 List<String> getCast() {
return cast;
}
public void setCast(List<String> cast) {
this.cast = cast;
}
}

要学习如何创建Java应用程序以使用MongoDB Extension for Hibernate ORM与此MongoDB示例集合交互,请参阅 入门教程

重要

持久性上下文

启用Hibernate ORM 能够与数据库交互,您必须使用 Hibernate Session 或 Jakarta Persistence EntityManager 在持久性上下文中运行操作。您还必须在ACID 事务中运行写入操作,才能修改MongoDB数据并保持数据完整性。

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();

要使用会话,您必须创建一个配置HibernateUtil.javaSessionFactory 文件。要学习;了解更多信息,请参阅入门教程中的配置应用程序步骤。

// 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;

要使用EntityManager ,您必须创建一个声明持久性单元的persistence.xml 文件。要学习;了解更多信息,请参阅 Hibernate ORM 文档中的使用 JPA 标准 API 的教程。

要将文档插入集合,请创建一个新的实体实例。然后,您可以将此实例作为参数传递给以下方法,以将其作为文档保存到MongoDB集合中:

  • org.hibernate.Session.persist():使用 Hibernate API应用更改应用于数据库

  • jakarta.persistence.EntityManager.persist():使用 Jakarta Persistence API应用更改应用于数据库

提示

要学习;了解有关创建实体实例并将其持久保存到数据库的更多信息,请参阅 Hibernate ORM 用户指南中的持久化实体

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(List.of("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(List.of("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);

要从集合中检索文档,请将查询条件传递给 createQuery() 方法。以下 API 均提供 createQuery() 方法:

  • Hibernate 的 Session API:使用 Hibernate 查询语言 (HQL) 语法定义查询

  • Jakarta Persistence 的 EntityManager API:使用 Jakarta Persistence Query Language (JPQL) 语法(HQL 的子集)来定义查询

提示

要学习有关使用 HQL 和 JPQL 语法检索数据的更多信息,请参阅 Hibernate ORM 查询指南中的 Select 声明

注意

本部分介绍如何使用 HQL 和 JPQL 读取文档,但您也可以使用条件构建器或原生查询来检索数据。要学习;了解详情,请参阅以下指南:

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

提示

查询语法

要学习;了解有关 HQL 和 JPQL 语法的更多信息,请参阅 Hibernate ORM 文档中的 Hibernate 查询语言指南。

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

您可以执行以下操作来修改集合中的文档:

  • 更新一个文档:调用实体的 setter 方法来更改一个实体实例的字段值,然后使用会话或实体管理器来保存更改。

  • 更新多个文档:将更新声明传递给会话或实体管理器上的createQuery()createMutationQuery() 方法。然后,调用executeUpdate() 方法将更改应用到数据库。

提示

要学习;了解有关使用 Hibernate ORM 修改数据的更多信息,请参阅以下资源:

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);

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

您可以执行以下操作从集合中删除文档:

提示

要学习;了解有关使用 Hibernate ORM 删除数据的更多信息,请参阅以下资源:

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);

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

要学习有关使用 Hibernate ORM 执行 CRUD 操作的更多信息,请参阅以下资源:

To view more create, read, update, and delete examples, see the following sections of the Get Started tutorial:

要学习;了解有关使用 Hibernate ORM 扩展来运行查询的更多信息,请参阅以下指南:

后退

创建实体

在此页面上