'joinColumns in Hibernate for standard relations?

In the following example, there are 3 entities which have relations e.g. @ManyToMany, @OneToMany and @ManyToOne:

Student:

@Entity
@Data
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    private String name;


    @JsonIgnore
    @ManyToMany(mappedBy = "students")
    private Set<Subject> subjects = new HashSet<>();
}

Subject:

@Entity
@Data
public class Subject {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    private String name;


    @ManyToMany
    @JoinTable(
            name = "subject_student",
            joinColumns = @JoinColumn(name = "subject_id"),
            inverseJoinColumns = @JoinColumn(name = "student_id")
    )
    Set<Student> students = new HashSet<>();

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "teacher_id", referencedColumnName = "id")
    private Teacher teacher;
}

Teacher:

@Entity
@Data
public class Teacher {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;


    @JsonIgnore
    @OneToMany(mappedBy = "teacher")
    private Set<Subject> subjects;
}

1. In the subject entity, I tried to remove @JoinColumn and the related entities are connected as the example above:

@ManyToMany
@JoinTable(name="subject_student")
public Set<Student> students = new HashSet<>();

@ManyToOne(cascade = CascadeType.ALL)
private Teacher teacher;

So, if we want to use subject_id - student_id pair in subject_student table and use teacher_id in subject table as it is created in the example, can I use my simplified notation by removing @JoinColumn? Because, if there is not a special case, I think it is redundant to verbose notation of relations.

2. When I use the second approach, the columns are created as plural e.g. subjects_id - students_id in subject_student. So, can I prevent this and create them as in the previous example by using my approach?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source