jana jana - 30 days ago 7
Java Question

Hibernate One-To-Many JoinColumn with same name

Entity(name = "Assignment")
class Assignment {
@Id
private int id;

private String assignmentCode;

}

Entity(name = "Review")
class Review {
@Id
private int id;

private String assignmentCode;
}


I have 2 tables each with 2 columns as above.
I want to create a list of reviews in the assignment entity and these reviews are joined on the column assignmentCode.

In the Assignment, I defined as below :

@OneToMany(targetEntity = Review.class, fetch=FetchType.EAGER)
@JoinColumn(name="assignmentCode")
private List<Review> reviews = new ArrayList<Review>();


but when I retrieve Assignment assignment = session.findById(Assignment.class, id);
I'm getting the exception Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Ambiguous column name 'assignmentCode'

What's the correct to define the reviews collection?
I cannot change the table structures to have different column names.

Answer Source

The correct solution for this is (https://forum.hibernate.org/viewtopic.php?f=1&t=1044726&start=0&sid=2e66d1aff1017f61f574f00e58836988)

@Entity(name = "Assignment")
class Assignment {
   @Id
   private int id;

   private String assignmentCode;

   @OneToMany(mappedBy = "assignment")
   private List<Review> reviews = new ArrayList<Review>();

   public void addReview(Review review) {
        reviews.add(review);
        reviews.setPost(this);
    }

    public void removeReview(Review review) {
        reviews.remove(review);
        reviews.setAssignment(null);
    }

}

@Entity(name = "Review")
class Review {
   @Id
   private int id;

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(
      name = "assignmentCode", 
      referencedColumnName = "assignmentCode"
   )
   private Assignment assignment;
}