如何在数据库JAVA中的两个对象之间建立关系

时间:2018-11-20 00:47:52

标签: java database oop

我目前正在尝试在学生班和学科班之间建立联系。这就是我正在做的:

@服务 公共类StudentRegistrationService实现ApplicationRunner {

private final StudentRepository repository;
private final DisciplineRepository repository1;

public StudentRegistrationService(StudentRepository repository, DisciplineRepository repository1) {
    this.repository = repository;
    this.repository1 = repository1;
}

@Override
public void run(ApplicationArguments args) throws Exception {


    Scanner scanner = new Scanner(System.in);

    while (true) {
        String input = scanner.nextLine();
        String[] split = input.split(" ");

        String command = split[0];

        switch (command.toUpperCase()) {
            case "END":
                System.out.println("bye bye");
                return;
            case "STUDLIST":
                printAllStudents();
                break;
            case "STUDNEW":
                String[] studentDetails = Arrays.copyOfRange(split, 1, split.length);
                createNewStudent(studentDetails);
                break;
            case "DISCLIST":
                printAllDisciplines();
                break;
            case "DISCNEW":
                String[] disciplineDetails = Arrays.copyOfRange(split, 1, split.length);
                createNewDiscipline(disciplineDetails);
                break;
            case "STUDDISC":
                String[] studentAndDisciplineId = Arrays.copyOfRange(split, 1, split.length);
                studendAndDiscipline(studentAndDisciplineId);

                break;
            default:
                System.out.println("UNKNOWN command, try again!");
                break;
        }

    }

}


private void createNewDiscipline(String[] details) {
    int hours=Integer.parseInt(details[1]);
    repository1.save(new Discipline(details[0],hours));
}

private void printAllDisciplines() {

    Iterable<Discipline> allDisciplines = repository1.findAll();

    for (Discipline discipline : allDisciplines) {
        System.out.println(discipline);
    }
}

private void createNewStudent(String[] details) {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
    LocalDate localDate = LocalDate.parse(details[1], dtf);
    repository.save(new Student(details[0],localDate));
}

private void printAllStudents() {

    Iterable<Student> allStudents = repository.findAll();

    for (Student student : allStudents) {
        System.out.println(student);
    }
}

private void studendAndDiscipline(String[] details) {
    int studentId=Integer.parseInt(details[1]);
    int disciplineId=Integer.parseInt(details[2]);
    Student student=repository.findById(studentId);
    Discipline discipline=repository1.findById(disciplineId);
    student.addDiscipline(discipline);
}

}

在studentAndDiscipline中,我必须通过ID在学生和学科之间创建关系,但是我做错了。我尝试使用Optional <>,但也不起作用。

我的学生班: @实体 班级学生{

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


private String name;
private LocalDate enrollmentDate;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
List<Discipline> disciplines;


private Student() {
    // Required by Hibernate
}
public Student(String name, LocalDate enrollmentDate) {
    this.name = name;
    this.enrollmentDate = enrollmentDate;
}

void addDiscipline(Discipline discipline) {
    this.disciplines.add(discipline);
}

@Override
public String toString() {
    return "Student{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", enrollmentDate=" + enrollmentDate +
            ", disciplines=" + disciplines +
            '}';
}

}

我的学科班: @实体 课程纪律{

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


String name;
int credits;

private Discipline() {
    // Required by Hibernate
}
public Discipline(String name, int credits) {
    this.name = name;
    this.credits = credits;
}

@Override
public String toString() {
    return "Discipline{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", credits=" + credits +
            '}';
}

}

我的学生资料库:

interface StudentRepository extends CrudRepository<Student, Integer> {

}

我的纪律资料库:

interface DisciplineRepository extends CrudRepository<Discipline, Integer> {

}

1 个答案:

答案 0 :(得分:0)

private void studendAndDiscipline(String[] details) {
    int studentId=Integer.parseInt(details[1]);
    int disciplineId=Integer.parseInt(details[2]);
    Student student=repository.findById(studentId);
    Discipline discipline=repository1.findById(disciplineId);
    student.addDiscipline(discipline);
}

Discipline discipline=repository1.findById(disciplineId);,是不对的。 findById(ID id)将返回Optional<T>类型,您需要使用get()来获得T。  并且您应该确保纪律不为空。至少您需要像这样检查它

Student student=repository.findById(studentId).get();
Discipline discipline=repository1.findById(disciplineId).get();
if (discipline != null) {
    student.addDiscipline(discipline);
    System.out.println("Adding discipline to student.");
}

如果您确定学科不为空,则需要检查addDiscipline()实现。