可能是一个常见的问题,但无论如何:
假设我有一个简单的实体Task,其中包含Activity实体列表:
@Entity
@Table(name = "task")
public class Task {
@Id
@Column(name = "id")
private Integer id;
@OneToMany
@JoinColumn(name = "task_id")
private List<Activity> activities;
}
活动实体非常简单:
@Entity
@Table(name = "activity")
public class Activity {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "activity_type")
private int type;
}
这里我想做一些魔术 - 基于Activity类型我希望hibernate用不同的Activity实现填充Task.activities,例如如果Activity.type == 1,我想在那里有ActivityAImpl,如果是Activity。 type == 2 - 它应该是ActivityBImpl等等。基本上我的所有活动都会用一些方法“execute()”实现一个单独的接口。
希望有一个简单的解决方案。
感谢您的帮助!
答案 0 :(得分:1)
没有测试过,但我认为这应该有用......
@Entity
@Table(name = "activity")
@Inheritance
@DiscriminatorColumn(name = "activity_type", discriminatorType = DiscriminatorType.INTEGER)
public abstract class Activity {
@Id
@Column(name = "id")
private Integer id;
}
@Entity
@DiscriminatorValue("1")
public class ActivityImpl1 extends Activity {
}
@Entity
@DiscriminatorValue("2")
public class ActivityImpl2 extends Activity {
}
答案 1 :(得分:0)
查看@MappedSuperClass和@Discriminator注释。我猜这就是你要找的东西。这是一个example。
@Entity
@Table(name = "activity)
@Inheritance
@DiscriminatorColumn(name = "activity_type")
public abstract class Activity {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "activity_type")
private int type;
public abstract void execute();
}
@Entity
@DiscriminatorValue("1")
public class ActivityImplA extends Activity {
public void execute() {
.... Impl a
}
}
@Entity
@DiscriminatorValue("2")
public class ActivityImplB extends Activity {
public void execute() {
.... Impl b
}
}