一对多多对一映射,服务器尝试查找不存在的表

时间:2013-12-27 17:25:11

标签: sql database hibernate java-ee jpa

我有两个实体StudentGroup。有一个名为StudentGroup的第三个实体,其中包含对Student的引用,对GroupDate字段的引用。

我尝试在Student&之间实现一对多关系StudentGroup多对一反之亦然。同样的想法适用于Group& StudentGroup

Student 类:

@Entity
@Table(name = "student")
public class Student {
 @Id @GeneratedValue
 private int sid;

 @OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
 private Set<StudentGroup> studentGroups;

 //Setter & Getter

}

Group 类:是:

@Entity
@Table(name = "group")
public class Group {
 @Id @GeneratedValue
 private int gid;

 @OneToMany(mappedBy = "group", cascade = CascadeType.ALL)
 private Set<StudentGroup> studentGroups;

 //Setter & Getter

}

StudentGroup 类:

@Entity
 @Table(name = "student_groups")
 public class StudentGroup {
        @Id @GeneratedValue
        private int id;

        @Column(name = "lastChanged")
        private Timestamp lastChanged;

        @ManyToOne
        @JoinColumn(name="sid")
        private Student student;

        @ManyToOne
        @JoinColumn(name="gid")
        private Group group;
        //Setter & Getter
    }

映射定义:

<mapping class="com.my.db.Student" />
<mapping class="com.my.db.Group" />
<mapping class="com.my.db.StudentGroup" />

当我启动我的tomcat服务器时,我总是得到错误

 org.hibernate.HibernateException: Missing table: student_student_groups
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1302)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:509)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)

为什么服务器会尝试查找我未在任何地方定义的student_student_groups表?

1 个答案:

答案 0 :(得分:2)

在JPA中,如果你没有注释你与@JoinColumn的关系,为了在关系之间加入而创建一个连接表,在你的情况下,应该存在studentstudent_groups之间的连接表,如果您将hibernate.hbm2ddl.auto属性集添加到create也会创建一个连接表,但如果您想避免使用连接表,则可以在关系中使用@JoinColumn注释:
例如:

@OneToMany
@JoinColumn(name="COLUMN_NAME")