Entity manager java методы

Entity manager java методы

Interface used to interact with the persistence context. An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.

Method Summary

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Indicate to the entity manager that a JTA transaction is active and join the persistence context to it.

Lock an entity instance that is contained in the persistence context with the specified lock mode type.

Lock an entity instance that is contained in the persistence context with the specified lock mode type and with specified properties.

Читайте также:  Docker compose java example

Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type.

Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type and with specified properties.

Refresh the state of the instance from the database, using the specified properties, and overwriting changes made to the entity, if any.

Источник

Руководство по Hibernate EntityManager

Более того, мы можем получить доступ к контексту постоянства, используя API вEntityManager.

В этом руководстве мы рассмотрим конфигурацию, типы и различные APIEntityManager.

2. Maven Зависимости

Во-первых, нам нужно включить зависимости Hibernate:

 org.hibernate hibernate-core 5.4.0.Final 

Нам также необходимо будет включить зависимости драйверов в зависимости от используемой базы данных:

 mysql mysql-connector-java 8.0.13 

Зависимостиhibernate-core иmysql-connector-java доступны в Maven Central.

3. конфигурация

Теперь давайте продемонстрируемEntityManager, используя объектMovie, который соответствует таблице MOVIE в базе данных.

В этой статье мы будем использовать APIEntityManager для работы с объектамиMovie в базе данных.

3.1. Определение сущности

Давайте начнем с создания объекта, соответствующего таблице MOVIE, используя аннотацию@Entity:

@Entity @Table(name = "MOVIE") public class Movie < @Id private Long id; private String movieName; private Integer releaseYear; private String language; // standard constructor, getters, setters >

3.2. Файлpersistence.xml

КогдаEntityManagerFactory создан,the persistence implementation searches for the META-INF/persistence.xml file in the classpath.

Этот файл содержит конфигурацию дляEntityManager:

 Hibernate EntityManager Demo com.example.hibernate.pojo.Movie true        

Чтобы объяснить, мы определяем единицу постоянства, которая определяет базовое хранилище данных, управляемоеEntityManager.

Кроме того, мы определяем диалект и другие свойства JDBC базового хранилища данных. Hibernate не зависит от базы данных. Based on these properties, Hibernate connects with the underlying database.с

4. Контейнер и приложение, управляемыеEntityManager

В основномthere are two types of EntityManager – Container Managed and Application Managed.

Давайте подробнее рассмотрим каждый тип.

4.1. Контейнер под управлениемEntityManager

Здесь контейнер вводитEntityManager в наши корпоративные компоненты.

Другими словами, контейнер создает для насEntityManager изEntityManagerFactory:

@PersistenceContext EntityManager entityManager;

Это также означаетthe container is in charge of beginning, committing, or rolling back the transaction.

4.2. Управляемое приложениемEntityManager

И наоборот, здесь жизненным цикломEntityManager управляет приложение.

Фактически, мы создадим вручнуюEntityManager.. Кроме того, мы также будем управлять жизненным циклом созданных намиEntityManager.

Во-первых, давайте создадимEntityManagerFactory:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.example.movie_catalog");

Чтобы создатьEntityManager, мы должны явно вызватьcreateEntityManager() вEntityManagerFactory:

public static EntityManager getEntityManager()

5. Hibernate Entity Operations

APIEntityManager предоставляет набор методов. Мы можем взаимодействовать с базой данных, используя эти методы.

5.1. Постоянные сущности

Чтобы иметь объект, связанный с EntityManager, мы можем использовать методpersist():

После сохранения объекта в базе данных он находится в состоянииpersistent.

5.2. Загрузка объектов

Для получения объекта из базы данных мы можем использовать методfind().

Здесь метод выполняет поиск по первичному ключу. Фактически, метод ожидает тип класса сущности и первичный ключ:

public Movie getMovie(Long movieId)

However, if we just need the reference to the entity, we can use the getReference() вместо этого. По сути, он возвращает прокси для сущности:

Movie movieRef = em.getReference(Movie.class, new Long(movieId));

5.3. Отделение сущностей

В случае, если нам нужно отсоединить объект от контекста постоянства,we can use the detach() method. Мы передаем объект, который будет отсоединен, в качестве параметра методу:

Как только объект отсоединен от контекста постоянства, он будет в отключенном состоянии.

5.4. Слияние сущностей

На практике многие приложения требуют модификации сущности для нескольких транзакций. Например, мы можем захотеть получить сущность в одной транзакции для рендеринга в пользовательский интерфейс. Затем другая транзакция внесет изменения, сделанные в пользовательском интерфейсе.

В таких ситуациях мы можем использовать методmerge(). The merge method helps to bring in the modifications made to the detached entity, in the managed entity, if any:

5.5. Запросы для сущностей

Кроме того, мы можем использовать JPQL для запроса сущностей. Мы вызовемgetResultList() для их выполнения.

Конечно, мы можем использоватьgetSingleResult(),, если запрос возвращает только один объект:

public List queryForMovies()

5.6. Удаление сущностей

Дополнительноwe can remove an entity from the database using the remove() method. Важно отметить, что объект не отсоединяется, а удаляется.

Здесь состояние объекта меняется с постоянного на новое:

6. Заключение

В этой статье мы исследовалиEntityManager вHibernate. Мы рассмотрели типы и конфигурацию, а также узнали о различных методах, доступных в API для работы сpersistence context.

Как всегда, в статье доступен кодover at Github.

Источник

Entity manager java методы

Interface used to interact with the persistence context. An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.

Method Summary

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Indicate to the entity manager that a JTA transaction is active and join the persistence context to it.

Lock an entity instance that is contained in the persistence context with the specified lock mode type.

Lock an entity instance that is contained in the persistence context with the specified lock mode type and with specified properties.

Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type.

Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type and with specified properties.

Refresh the state of the instance from the database, using the specified properties, and overwriting changes made to the entity, if any.

Источник

Оцените статью