Skip to content
Advertisement

Can a Java hibernate/persistence entity have a related entity ID as well as the related entity?

Pretty simple setup, I have a building entity that belongs to an account. So the building entity looks like:

@Entity
@Table(name = "building")
public class Building extends BaseEntity {
    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "account_id", nullable = false)
    private Long accountId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "account_id")
    private Account account;
...

(BaseEntity provides id, created and lastModified columns)

I.e. The building has a name, the ID of the account it belongs to, and then the account entity that it belongs to. However, with this setup I’m getting errors when my Spring Boot application tries to start up:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: domain.Building column: account_id (should be mapped with insert="false" update="false")
org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:799) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:862) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:880) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:53) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
...

This seems like a legitimate setup – I want to be able to get the account ID off of an object without having to load the entire object (although in this case the FetchType is EAGER, so maybe it doesn’t matter so much), but I also want to be able to reference the full entity sometimes as well.

Am I missing something, or is this just not supported by Hibernate? Should I discard accountId and always pull it off of the account object if I need it?

Advertisement

Answer

It will work if you correct your mapping in this way:

@Column(name = "account_id", nullable = false, insertable = false, updatable = false)
private Long accountId;

Hibernate just can not understand what field should be used for the synchronization with database column account_id. You can use as many fields as you wish for representing the column value. But only one column can be taken into account for writing to this column.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement