2017-06-18 66 views
0

我有'課程'和'學生'實體。他們有多對多的關係。所以,我有COURSE_STUDENT(包含'student_id'和'course_id'列)表。我想用一個按鈕向學生註冊課程(例如,學生列出課程並點擊註冊按鈕註冊特定課程)。 當我想創建新課程時,我默認使用來自JHipster的courseRepository和courseMapper。 但我沒有COURSE_STUDENT的存儲庫和映射器文件。因爲它實際上不是一個主要實體。它是爲多對多關係而創建的。 我如何註冊學生課程?將數據註冊到多對多關係表中

混帳回購協議:https://github.com/canberkizgi/monolithic-mucs

我的課程實體:

@Entity 
@Table(name = "course") 
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 
public class Course implements Serializable { 

private static final long serialVersionUID = 1L; 

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

@NotNull 
@Column(name = "title", nullable = false) 
private String title; 

@Column(name = "description") 
private String description; 

@ManyToOne 
private Instructor instructor; 

@ManyToMany(fetch = FetchType.EAGER) 
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 
@JoinTable(name = "course_student", 
      joinColumns = @JoinColumn(name="courses_id", referencedColumnName="id"), 
      inverseJoinColumns = @JoinColumn(name="students_id", referencedColumnName="id")) 
private Set<Student> students = new HashSet<>(); 

學生實體:

@Entity 
@Table(name = "student") 
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 
public class Student implements Serializable { 

private static final long serialVersionUID = 1L; 

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

@OneToOne 
@JoinColumn(unique = true) 
private User user; 

@ManyToMany(fetch = FetchType.EAGER,mappedBy = "students") 
@JsonIgnore 
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 
private Set<Course> courses = new HashSet<>(); 

例如;使用Mapper和知識庫的Createcourse功能

@PostMapping("/courses") 
@Timed 
public ResponseEntity<CourseDTO> createCourse(@Valid @RequestBody CourseDTO courseDTO) throws URISyntaxException { 
    log.debug("REST request to save Course : {}", courseDTO); 
    if (courseDTO.getId() != null) { 
     return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new course cannot already have an ID")).body(null); 
    } 
    Course course = courseMapper.toEntity(courseDTO); 
    course = courseRepository.save(course); 
    CourseDTO result = courseMapper.toDto(course); 
    return ResponseEntity.created(new URI("/api/courses/" + result.getId())) 
     .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) 
     .body(result); 
} 

回答

0

該關係由課程實體擁有。那是因爲在學生方面,@ManyToMany註釋具有mappedBy屬性。這意味着,數據庫將反映課程中的設置。您需要將學生添加到該設置以保存關係。這種變化需要在交易中完成。

這是說,它可能是最好的遵循DDD在這裏。我將在學生課程中創建一個registerTo方法,將該課程作爲參數。然後我會在該方法中調用this.courses.add(course)course.getStudents().add(this)