Search code examples
javaspringhibernaterelationshiphibernate-mapping

Hibernate creates redundant column in database


I work at a room-management software in which I want to know the rooms in a certain building.

In the building entity the @OneToMany relationship:

   @JsonBackReference(value= "room")
   @OneToMany(targetEntity=Room.class, mappedBy="building", fetch=FetchType.EAGER,cascade = 
              CascadeType.REMOVE,orphanRemoval = true)
   public Set<Room> getRooms() {
       return this.rooms;
}

And in the room entity the @ManyToOne relationship:

@JsonManagedReference(value= "room")
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="building_number", nullable=false)
@OnDelete(action = OnDeleteAction.CASCADE)
public Building getBuilding() {
    return this.building;
}

And the auto-generated database generates an extra field because of those relationships and I just want them to be mapped on Room.building_number:

building_building_number and I just need building_number.


Solution

  • Try use something like that:

    Building.class:

    @OneToMany(mappedBy="building")
    private Set<Room> rooms;
    
    // getters and setters
    

    Room.class:

    @ManyToOne
    @JoinColumn(name="building_number", nullable=false)
    private Building building;
    
    // getters and setters