Search code examples
javahibernatehibernate-mapping

Hibernate Mapping same Column twice and insert


I want to insert a row that contain two filed name organization_id and account_id that is refereed from same table (organization table).

EntityModel.java

@ManyToOne
@JoinColumn(name = "organization_id")
private OrganizationModel organization;

@ManyToOne
@JoinColumn(name = "account_id")
private OrganizationModel account;

OrganizationModel.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "organization_id", unique = true, nullable = false)
private int organizationId;

@OneToMany(mappedBy = "organization")
private Set<EntityModel> organization;

But iam getting following error.

Repeated column in mapping for entity: com.party.OrganizationModel column: organization_id (should be mapped with insert="false" update="false")

And when i add insert="false" update="false" for account, error gone.But i need to insert both account and organization at the same time.


Solution

  • Add a primary key for EntityModel.

    Here is the code that worked for me:

    @Entity
    @Table(name = "EntityModel")
    public class EntityModel {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "entity_model_id", unique = true, nullable = false)
        private int entityModelId;
    
        @ManyToOne
        @JoinColumn(name = "organization_id")
        private OrganizationModel organization;
    
        @ManyToOne
        @JoinColumn(name = "account_id")
        private OrganizationModel account;
    
    }
    
    @Entity
    @Table(name = "OrganizationModel")
    public class OrganizationModel {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "organization_id", unique = true, nullable = false)
        private int organizationId;
    
        @OneToMany(mappedBy = "organization")
        private Set<EntityModel> organization;
    
    }