这是两个实体类,分别是学生和老师
这是错误信息
org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: com.model.Teacher.students
老师类
- Java code
package com.model;import java.util.HashSet;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Teacher { private int id; private String name; private HashSet<Student> students = new HashSet<Student>(); @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToMany public HashSet<Student> getStudents() { return students; } public void setStudents(HashSet<Student> students) { this.students = students; }}
===================================================================================
===================================================================================
学生类
- Java code
package com.model;import java.util.HashSet;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Student { private int id; private String name; private HashSet<Teacher> teahcers = new HashSet<Teacher>(); @ManyToMany(mappedBy="students") public HashSet<Teacher> getTeahcers() { return teahcers; } public void setTeahcers(HashSet<Teacher> teahcers) { this.teahcers = teahcers; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
------解决方案--------------------
看代码好似乎没问题哦。不知道那里有问题。
------解决方案--------------------
------解决方案--------------------
最好不要用“ManyToMany”,因为中间表往往还有其他字段。
------解决方案--------------------
Hibernate 中不能使用实体类的,要用接口