📜  spring jpa 向多对多表添加字段 - Java (1)

📅  最后修改于: 2023-12-03 15:05:16.196000             🧑  作者: Mango

Spring JPA向多对多表添加字段

在Spring JPA中,我们可以使用@ManyToMany注释来实现多对多的关系,同时使用中间表来连接两个实体类之间的关系。但是,在使用中间表时,我们有时需要在中间表中添加一些字段,这时就需要创建一个新的实体类来代表中间表,并在实体类之间建立多对多关系。下面是一些示例代码来说明如何向多对多关系的中间表中添加字段。

定义实体类和中间表实体类

我们需要定义两个实体类和一个中间表实体类,比如:

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "students")
    private List<Course> courses = new ArrayList<>();
}

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(
        name = "course_student",
        joinColumns = @JoinColumn(name = "course_id"),
        inverseJoinColumns = @JoinColumn(name = "student_id")
    )
    private List<Student> students = new ArrayList<>();
}

@Entity
public class CourseStudent {
    @EmbeddedId
    private CourseStudentId id;

    private int score;

    public CourseStudent() {}

    public CourseStudent(Course course, Student student, int score) {
        this.id = new CourseStudentId(course.getId(), student.getId());
        this.score = score;
    }
}

@Embeddable
public class CourseStudentId implements Serializable {
    private Long courseId;

    private Long studentId;

    public CourseStudentId() {}

    public CourseStudentId(Long courseId, Long studentId) {
        this.courseId = courseId;
        this.studentId = studentId;
    }

    // getters and setters
}
定义仓库类和服务类

我们需要创建仓库类和服务类,比如:

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {}

@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {}

@Service
public class CourseStudentService {
    @Autowired
    private CourseStudentRepository courseStudentRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StudentRepository studentRepository;

    public void addScore(Long courseId, Long studentId, int score) {
        Course course = courseRepository.findById(courseId).orElse(null);
        Student student = studentRepository.findById(studentId).orElse(null);

        if (course != null && student != null) {
            CourseStudent courseStudent = new CourseStudent(course, student, score);
            courseStudentRepository.save(courseStudent);
        }
    }
}

@Repository
public interface CourseStudentRepository extends JpaRepository<CourseStudent, CourseStudentId> {}
测试添加字段

最后,我们可以在测试类中测试是否添加了字段,比如:

@SpringBootTest
public class CourseStudentServiceTest {
    @Autowired
    private CourseStudentService courseStudentService;

    @Autowired
    private CourseStudentRepository courseStudentRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Test
    public void testAddScore() {
        Course course = new Course();
        course.setName("Math");

        Student student = new Student();
        student.setName("Tom");

        courseRepository.save(course);
        studentRepository.save(student);

        course.getStudents().add(student);
        student.getCourses().add(course);

        CourseStudent courseStudent = new CourseStudent(course, student, 90);
        courseStudentRepository.save(courseStudent);

        assertNotNull(courseStudent);
        assertEquals(courseStudent.getScore(), 90);
    }
}

以上就是向Spring JPA的多对多关系的中间表中添加字段的一些示例代码。