Java entity without id

JPA entity without id

I know that JPA entities must have a primary key but I can’t change the database schema due to reasons that are beyond my control. Is it possible to create JPA (Hibernate) entities that will work with database schema like this?

mikhail

People also ask

JPA requires that every entity has an ID. So no, entity w/o an ID is not allowed. Every JPA entity must have a primary key.

If your object does not have an id, but its’ table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the «Jpa Id» is the combination of all columns.

3 Answers

I guess your entity_property has a composite key (entity_id, name) where entity_id is a foreign key to entity . If so, you can map it as follows:

@Embeddable public class EntityPropertyPK < @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "entity_id") private Entity entity; . >@Entity @Table(name="entity_property") public class EntityProperty

axtavt

I know that JPA entities must have primary key but I can’t change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id .

And if your table has some id but your entity doesn’t, make it an Embeddable .

Pascal Thivent

See the Java Persistence book: Identity and Sequencing

The relevant part for your question is the No Primary Key section:

Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object’s row, so all of the matching rows will be updated or deleted.

If your object does not have an id, but its’ table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Gilberto Avatar

answered Sep 17 ’22 19:09

Источник

JPA сущность без идентификатора

Я знаю, что сущности JPA должны иметь первичный ключ, но я не могу изменить структуру базы данных по причинам, не зависящим от меня. Возможно ли создать объекты JPA (Hibernate), которые будут работать с структурой базы данных следующим образом?

5 ответов

Я думаю, ваш entity_property имеет составной ключ (entity_id, name) , где entity_id является внешним ключом для entity . Если это так, вы можете отобразить его следующим образом:

@Embeddable public class EntityPropertyPK < @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "entity_id") private Entity entity; . >@Entity @Table(name="entity_property") public class EntityProperty

Благодарю. Но как в этом случае получить прямой доступ к свойству name? Мой запрос JP-QL работает хорошо только при доступе к «имени» через «entity.id.name», но я думаю, что это неправильно.

@mikhail: Если вам не нравится подход с @EmbeddedId , вы можете попробовать альтернативный подход с @IdClass : : docs.jboss.org/hibernate/stable/annotations/reference/en/…

@mikhail: Если вам не нравится подход с @EmbeddedId , вы можете попробовать альтернативный подход с @IdClass : : docs.jboss.org/hibernate/stable/annotations/reference/en/…

Да, аннотация для EntityPropertyPK должна быть @Embeddable поскольку @Embedded можно применять только к полям и методам. Более того, класс EntityPropertyPK должен быть объявлен как Serializable .

Что делать, если у меня нет ключей в базе данных и изменение схемы запрещено? Таблица с date и some_int например?

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

Точнее, объект JPA должен иметь определенный Id . Но JPA Id необязательно должен отображаться в первичном ключе таблицы (и JPA может каким-то образом иметь дело с таблицей без первичного ключа или уникального ограничения).

Возможно ли создать объекты JPA (Hibernate), которые будут работать с структурой базы данных, как это?

Если у вас есть столбец или набор столбцов в таблице, которые делают уникальное значение, вы можете использовать этот уникальный набор столбцов в качестве Id в JPA.

Если в вашей таблице нет уникальных столбцов, вы можете использовать все столбцы как Id .

И если ваша таблица имеет некоторый идентификатор, но ваша сущность не делает этого, сделайте его Embeddable .

пожалуйста, я новичок как я могу использовать все столбцы в качестве идентификатора в сущности на этом небольшом примере: int SIN, int age, String name, String adresse. благодарю вас

Соответствующей частью вашего вопроса является No Primary Key section:

Иногда ваш объект или таблица не имеют первичного ключа. Лучшее решение в этом случае обычно добавляется сгенерированный идентификатор к объекту и Таблица. Если у вас нет этой опции, иногда есть столбец или набор столбцов в таблице, которые составляют уникальное значение. Вы можете использовать этот уникальный набор столбцов как ваш идентификатор в JPA. JPA Id не всегда должен соответствовать первичному ключу таблицы базы данных ограничение, а также не является первичным ключом или требуемым уникальным ограничением.

Если ваша таблица действительно не имеет уникальных столбцов, используйте все столбцы как идентификатор. Обычно, когда это происходит, данные доступны только для чтения, поэтому даже если таблица позволяет дублировать строки с одинаковыми значениями, объекты будет одинаковым в любом случае, поэтому не имеет значения, что JPA считает, что они являются одним и тем же объектом. Проблема с разрешениями и удалениями что нет возможности однозначно идентифицировать строку объекта, поэтому все соответствующие строки будут обновлены или удалены.

Если ваш объект не имеет идентификатора, но его «таблица», это нормально. Сделать объект объектом Embeddable , встраиваемыми объектами не имеют идентификаторов. Вам понадобится Entity , который содержит это Embeddable , чтобы продолжить и запросить его.

Источник

Using Spring Data for database views without an ID

A database view is a great way to prepare complicated data structures and present it in a more convenient way. We can use database views to map our technical driven database structure (with a lot of tables and foreign keys) to a more business driven structure. This means that we might join tables, concatenate values or just rename the columns, because a particular name suits better to the current business context.

CREATE OR REPLACE VIEW COMPANY_TO_PERSON AS SELECT COMPANY.NAME AS COMPANY_NAME, PERSON.NAME AS PERSON_NAME FROM COMPANY LEFT JOIN PERSON ON COMPANY.COMPANY_ID = PERSON.COMPANY_ID; 

To map those views to Java entities, we can use Spring Data:

@Entity @Table(name = "COMPANY_TO_PERSON") // A view! public class Company2Person  // This won't work as the entity has no @Id! @Column(name = "COMPANY_NAME") private String companyName; @Column(name = "PERSON_NAME") private String personName; // getter and setter. > 

However, the example above wouldn’t work. Spring will complain that the @Id annotation is missing and would throw a org.hibernate.AnnotationException: No identifier specified for entity exception.

From a business perspective, this is bad. The id of a company is its company id, the id of a person is its person id. But both are missing in the view, which has no unique identifier.

We could solve this problem by a simple trick: we invent a unique identifier — our current row number!

CREATE OR REPLACE VIEW COMPANY_TO_PERSON AS SELECT rownum AS ID, COMPANY.NAME AS COMPANY_NAME, PERSON.NAME AS PERSON_NAME FROM COMPANY LEFT JOIN PERSON ON COMPANY.COMPANY_ID = PERSON.COMPANY_ID; 

We can now use the row number in our Spring Data entity:

@Entity @Table(name = "COMPANY_TO_PERSON") // A view! public class Company2Person  @Id @Column(name = "ID") private Long id; // The row number! @Column(name = "COMPANY_NAME") private String companyName; @Column(name = "PERSON_NAME") private String personName; // getter and setter. > 

Best regards, Thomas.

We would like to use third party cookies and scripts to improve the functionality of this website. See our privacy policy.
Approve Reject —>

Источник

[java] JPA entity without id

I know that JPA entities must have a primary key but I can’t change the database schema due to reasons that are beyond my control. Is it possible to create JPA (Hibernate) entities that will work with database schema like this?

This question is related to java hibernate jpa

The answer is

I guess your entity_property has a composite key (entity_id, name) where entity_id is a foreign key to entity . If so, you can map it as follows:

@Embeddable public class EntityPropertyPK < @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "entity_id") private Entity entity; . >@Entity @Table(name="entity_property") public class EntityProperty

I know that JPA entities must have primary key but I can’t change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id .

And if your table has some id but your entity doesn’t, make it an Embeddable .

The relevant part for your question is the No Primary Key section:

Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object’s row, so all of the matching rows will be updated or deleted.

If your object does not have an id, but its’ table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of «entity properties» to a List in entity .

You can create the EntityProperty type and annotate it with @Embeddable

If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.

Источник

Читайте также:  Java util set clear
Оцените статью