1

There are tables linked by ManyToOne. Each Student is assigned one direction from EducationDirections. When I create a student, the selected direction is re-created. Why is a direction being created when a Student is created?
Student:

@Entity
public class Student {

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

    @NotEmpty(message = "Введите имя!")
    @Size(min = 2, max = 50, message = "Максимально допустимая длина 50!")
    private String name;

    @NotEmpty(message = "Введите фамилию!")
    @Size(min = 2, max = 50, message = "Максимально допустимая длина 50!")
    private String surname;

    @NotEmpty(message = "Введите отчество!")
    @Size(min = 2, max = 50, message = "Максимально допустимая длина 50!")
    private String patronymic;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "direction_id")
    private EducationDirections educationDirection;
    //getters and setters

EducationDirections:

@Entity
public class EducationDirections {

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

   @NotEmpty
   private String program;

   @OneToMany(mappedBy = "educationDirection", cascade = CascadeType.ALL)
   private List<Student> students;
   //getters and setters

StudentDAO:

@Component
public class StudentDAO {

    private final SessionFactory sessionFactory;

    public StudentDAO(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Transactional
    public void create (Student student) {
        Session session = sessionFactory.getCurrentSession();
        session.save(student);
    }
}
Gasan
  • 11
  • 2

0 Answers0