日期:2014-05-20  浏览次数:20653 次

大哥们帮帮看看错在哪里 hibernate Annotation 老师 学生 的多对多双向
这是两个实体类,分别是学生和老师


这是错误信息
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;

@Entity
public 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;

@Entity
public 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;
    }
    
}






------解决方案--------------------
看代码好似乎没问题哦。不知道那里有问题。
------解决方案--------------------
探讨
发现在问题了:

集合必要为Set ,我弄成HashSet了。

大家可以试一下我这个,看看。

------解决方案--------------------
最好不要用“ManyToMany”,因为中间表往往还有其他字段。
------解决方案--------------------
Hibernate 中不能使用实体类的,要用接口