如何在 Hibernate 中映射没有 id 的抽象 class

How to map an abstract class without an id in Hibernate

这个项目的背景是,有两种用户,susciber用户和amdin用户。还有两种类型的订阅者用户,学生和教授。管理员用户可以注册新的 class 房间,订阅者用户可以订阅 class 房间以查看不同的信息,例如温度等。

问题是我必须在教室和订户用户之间映射 ManyToMany 双向关系,我在教室中收到以下错误 class:

'Many To Many' attribute value type should not be 'SuscriberUser'

这个例外:

org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class

这是我的代码:

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class User implements IUser {
    private String name;

    // some other fields
    // constructors
    // getters and setters
}
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuscriberUser extends User implements ISuscriberUser {
    @ManyToMany(mappedBy = "suscribers")
    private ArrayList<Classroom> classroomSubscriptions;

    // constructors
    // getters and setters
}

例如 SuscriberUser 的具体 class:

@Entity
@Table(name = "student")
public class Student extends SuscriberUser {
    @Id
    private int studentId;

        // constructors
        // getters and setters
}
@Entity
@Table(name = "classroom")
public class Classroom implements IClassroom {
    @Id
    private int internalId;

    // other fields

    @ManyToMany()
    @JoinTable(name = "suscribers")
    private ArrayList <SuscriberUser> suscribers;

    // constructors
    // getters and setters
}

我也曾尝试在 classes User 和 SuscriberUser 中使用 @MappedSuperclass,但它不起作用。我想这是因为两个抽象 classes 都没有 id。

我该如何解决这个问题?

Userclass只是一个字段的收集器,所以可以变成@MappedSuperClass

@MappedSuperClass
public abstract class User implements IUser {
    
    private String name;

    // some other fields
    // constructors
    // getters and setters
}

如果您使用 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS),则每个 class 都有一个 table,因此您需要:

  1. 移除abstract
  2. 添加@Entity注释
  3. 添加@Table定义名称
  4. @Id 添加到 id 列。
@Entity
@Table(name = "subscriber_user")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class SuscriberUser extends User implements ISuscriberUser {

    @Id
    private int id;
    
    @ManyToMany(mappedBy = "suscribers")
    private List<Classroom> classroomSubscriptions;

    // constructors
    // getters and setters
}

更多信息here

学生 class 不需要 id 列,因为在父 class 中。

@Entity
@Table(name = "student")
public class Student extends SuscriberUser {

        // constructors
        // getters and setters
}

注意连接table是另一个。这个table包含了学生和class房间的关系,可以命名为subscription.

@Entity
@Table(name = "classroom")
public class Classroom implements IClassroom {
    @Id
    private int internalId;

    // other fields

    @ManyToMany
    @JoinTable(
        name = "subscription", 
        joinColumns = @JoinColumn(name = "internalId"), // id class room
        inverseJoinColumns = @JoinColumn(name = "id")) // id user
    private List<SuscriberUser> suscribers;

    // constructors
    // getters and setters
}