在使用hibernate over MySQL的spring mvc应用程序中,当我试图创建从aid继承其BaseEntity的多态子类时,遇到了问题。当您阅读下面的myAccessLog类时,您可以看到我的预期用途,该类具有BaseEntity类型的属性。actor_entitytarget_entity属性都应该可以填充各种不同类型的实体,例如UserOutsideSystemDocument等,每个实体都继承自BaseEntity
如何在代码中设置?
这是我当前的java:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    protected Integer id;
    //other stuff
}

@Entity
@Table(name="users")
public class User extends BaseEntity{
    //other stuff
}

@Entity
@Table(name = "accesslogs")
public class AccessLog extends BaseEntity{

    @ManyToOne
    @JoinColumn(name = "actorentity_id")
    private BaseEntity actor_entity;

    @ManyToOne
    @JoinColumn(name = "targetentity_id")
    private BaseEntity target_entity;

    @Column(name="action_code")
    private String action;
}

这是我当前的DDL:
CREATE TABLE IF NOT EXISTS baseentity(
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
)engine=InnoDB;SHOW WARNINGS;

CREATE TABLE IF NOT EXISTS accesslogs(
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  actorentity_id int(11) UNSIGNED NOT NULL,
  targetentity_id int(11) UNSIGNED NOT NULL,
  action_code varchar(100),
  access_date DATETIME
)engine=InnoDB;SHOW WARNINGS;

CREATE TABLE roles (
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  role varchar(20) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE users (
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  login varchar(20) NOT NULL,
  password varchar(20) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE user_roles (
  user_id int(11) UNSIGNED NOT NULL,
  role_id int(11) UNSIGNED NOT NULL,
  KEY user (user_id),
  KEY role (role_id)
) ENGINE=InnoDB;

最佳答案

为什么需要用实体对BaseEntity进行注释?不需要指定@Inheritance(strategy=InheritanceType.JOINED)。BaseEntity应具有@MappedSuperclass注释
不需要创建baseentity表

10-04 20:40