2016-08-19 3 views
0

JPA의 일대일 작업, 읽은 모든 문서, 예제에서 일대일 다 대다 대 일대일을 혼동하는 방식으로 정말 혼란 스럽습니다. 아니, 그리고 그것을 시도했을 때 작동하지 않습니다.JPA Hibernate one to many

제 질문은 두 개의 테이블이 있다고 가정하고, findCollegeData() 메소드를 사용하여 College 객체를 채우고 싶습니다. 그러면 객체를 초기화 할 때이 대학의 모든 학생이 목록에 포함됩니다.

다음은 내 접근 방식입니다. storeCollegeData() 메소드를 사용하여 모든 학생을 대학 목록에 저장할 수 있지만 대학 개체를 완전히 검색 할 수는 없습니다. 학생 목록은 항상 비어 있습니다. 데이터베이스에 있으며 대학 이름을 사용하여 학생을 직접 검색하려고하면 작동합니다.

public static EntityManager entityManager = something; 

@Entity 
@Data 
@NoArgsConstructor 
@AllArgsConstructor 
public College { 
    @Id 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    private int cId; 
    private String collegeName; 
    private int numOfStudent; 

    @OneToMany(mappedBy="collegeName", cascade=CascadeType.ALL, orphanRemoval=true) 
    private List<Student> studentList = new ArrayList<>(); 
} 


@Entity 
@Data 
@NoArgsConstructor 
@AllArgsConstructor 
public Student { 
    @Id 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    private int sId; 
    private String name; 
    private String collegeName; 
    private String city; 
} 


// college.getStudentList is always empty and I don't know why 
public findCollegeData(String collegeName) { 
    College college = entityManager.find(College.class, collegeName); 
} 

// Student data in the studentList are inserted into student table 
public storeCollegeData(College college) { 
    entityManager.persist(college); 
} 

// This method works 
public findStudent(String collegeName) { 

    CriteriaBuilder cb = provider.get().getCriteriaBuilder(); 
    CriteriaQuery<Student> query = cb.createQuery(Student.class); 
    Root<Student> student = query.from(Student.class); 

    query.where(
      cb.and(
        cb.equal(student.get("collegeName"), collegeName) 
      ) 
    ); 

    JobStatisticDB Student = provider.get().createQuery(query).getSingleResult(); 
} 

나는 뭔가를 놓치고 있습니까 ??? 여기의지도보다 조인이 더 적절합니까 ??? 내가 편집 사람에게

을 할 와트 몰라 : 은 내가 시드와 시드를 추가 할 수있는 방법, 그러나하지만, @Id 주석을 추가하여 테이블의 기본 키로 collegeName 모두를 변경하여 작업을 알았어요 테이블, 그래서 그들은 중복 대학 이름을 가질 수 ???? 지금 당장에는 같은 이름의 중복 대학과 같은 대학에 다니는 학생을 가질 수 없습니다!

최종 편집 : 변경된 데이터베이스 설계가 College의 id 필드에 동일시 값을 포함해야

답변

1

대답이 잘못되었습니다. 엔티티 사이의 관계를 정의합니다. 매핑은 양방향 @OneToMany

대학에 대해 다음과 같이해야한다 :

@Entity 
@Data 
@NoArgsConstructor 
@AllArgsConstructor 
public College { 
    @Id 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    private int cId; 
    private String collegeName; 
    private int numOfStudent; 

    @OneToMany(mappedBy="college", cascade=CascadeType.ALL, orphanRemoval=true) 
    private List<Student> studentList = new ArrayList<>(); 
} 

학생 :

public findCollege(int collegeId) { 
    College college = entityManager.find(College.class, collegeId); 
    college.getStudents(); //will be populated 
} 

public findStudent(int studentId) { 
    Student student = entityManager.find(Student.class, studentId); 
    student.getCollege(); //will be populated 
    student.getCollege().getStudents(); //will be populated 
} 
:

@Entity 
@Data 
@NoArgsConstructor 
@AllArgsConstructor 
public Student { 
    @Id 
    @GeneratedValue(strategy= GenerationType.AUTO) 
    private int sId; 
    private String name; 
    private String city; 

    //student table has a FK column college_id 
    @ManyToOne 
    @JoinColumn(name = "college_id") 
    private College college; 
} 

의 EntityManager()을 찾을 수는 인수로 PK 소요

이름으로 대학을 찾으려면 JPQL 또는 Criteria 쿼리를 만듭니다.

+0

그러나 나는 FK 컬럼을 가지고 있지 않다. 단지 내가 지정한 coloum에 그것들을 합치기를 원한다. 이 경우 대학 이름 coloum에 가입하길 원합니다 –

+1

데이터베이스를 재 설계하십시오. Hibernate는 Object Relational Mapper입니다. 현재 관계형 데이터베이스가 없습니다. –

+0

작동하도록했습니다. 감사합니다. –

1

다음은 mappedBy에서 참조 필드를 외래 키 참조 솔루션을 사용합니다. city 대신 collegeName으로 변경하면 제대로 작동합니다.

+0

지도를 대학 이름으로 변경했습니다. 작동하지 않지만, 이제는 cId 멤버를 추가하면 작동하지 않습니다. 그리고 2id를 cid와 collegeName에 추가하면 오류가 발생합니다. "외래 키는 참조 된 기본 키와 동일한 수의 열을 가져야합니다."그리고 cId 멤버를 제거하고 collegeName을 ID로 유지하면 데이터베이스에 데이터를 삽입 할 수없는 것처럼 보입니다. –

+0

nvm 제대로 작동하는 것 같습니다. , 나는 둘 다 className을 두 클래스의 ID로 변경했습니다. 그런 다음 매핑 할 수 있습니다. 그러나 두 키가 모두 기본 키이기 때문에 같은 이름의 중복 된 대학을 가질 수는 없습니다. 정말 형제입니다. @id 회원, 나는 그것에 복합 키 매핑 오류, 어떤 해결책을 얻을 것인가? –

+0

죄송 합니다만이 답변이 잘못되었습니다. –