[英]JPA Hibernate one to many
我對JPA中一對多的工作方式感到困惑,我閱讀的所有文檔在其示例中都使用了一對多和多對一的方式,而且我不知道它們是否是必需的,並且不起作用當我嘗試過。
我的問題是,假設我有兩個表,並且我想使用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();
}
我想念什么嗎??? 加入比這里的地圖更合適嗎??? 我不知道做男人的w
編輯:通過添加@Id批注將兩個collegeName更改為表的主鍵,使其起作用,但是,如何將sId和cId添加到表中,以便它們可以具有重復的大學名稱? 現在,我不能有重復的同名大學和去同一所大學的學生!
最終編輯:更改數據庫設計以使用外鍵,請參見下面的解決方案
您在mappedBy
引用的字段必須包含等於College
的id字段的值。 將其更改為collegeName
而不是city
,它應該可以工作。
接受的答案不正確:您定義了實體之間的關系。 雙向@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<>();
}
學生:
@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 find()將PK作為參數:
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
}
如果要按名稱查找大學,請創建JPQL或Criteria查詢:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.