我已经阅读了 Hibernate
的 O/R Mapping,但我似乎无法理解 polymorphism
的部分。
根据https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch05.html ,
Implicit polymorphisms means that instances of the class will be returned by a query that names any superclass or implemented interface or class, and that instances of any subclass of the class will be returned by a query that names the class itself
鉴于
Explicit polymorphisms means that class instances will be returned only by queries that explicitly name that class. Queries that name the class will return only instances of subclasses mapped
我只想了解这两个是如何工作的。有人可以通过使用代码的示例(不必太复杂)来解释这些术语吗?我会很感激你的帮助
最佳答案
首先 org.hibernate.annotations.Entity
注释是 deprecated现在。你应该使用 @Polymorphism注释代替。
现在,假设您有以下架构:
create table TST_STUDENT
(
st_id int not null,
st_name varchar(200),
primary key (st_id)
);
insert into TST_STUDENT values (1, 'Kostya'), (2, 'Yulia'), (3, 'Borya'), (4, 'Misha');
create table TST_TEACHER
(
tcr_id int not null,
tcr_first_name varchar(200),
tcr_last_name varchar(200),
primary key (tcr_id)
);
insert into TST_TEACHER values (1, 'Mikhail', 'Bulgakov'), (2, 'Leo', 'Tolstoy');
和以下映射:
public interface Person
{
Long getId();
String getName();
}
@Entity
@Table(name = "TST_STUDENT")
public class Student implements Person
{
@Id
@Column(name = "st_id")
private Long id;
@Column(name = "st_name")
private String name;
public Student()
{
}
// getters / setters
}
和老师
实体:
import org.hibernate.annotations.Polymorphism;
import org.hibernate.annotations.PolymorphismType;
@Entity
@Table(name = "TST_TEACHER")
// @Polymorphism(type = PolymorphismType.EXPLICIT)
public class Teacher implements Person
{
@Id
@Column(name = "tcr_id")
private Long id;
@Column(name = "tcr_first_name")
private String name;
@Column(name = "tcr_last_name")
private String lastName;
public Teacher()
{
}
// getters / setters
}
现在,如果您运行以下查询:
List<Person> persons = em.createQuery("select p from com.your.entities.Person p", Person.class).getResultList();
您将获得 TST_STUDENT
表中的所有行以及 TST_TEACHER
表中的所有行。
但是,如果您取消注释这一行:
@Entity
@Table(name = "TST_TEACHER")
@Polymorphism(type = PolymorphismType.EXPLICIT) // now we use explicit polymorphism for the Teacher entity
public class Teacher implements Person
上面提到的查询将只返回 TST_STUDENT
表中的行。
这就是这个注解的意思。
默认情况下,当您查询基类实体时,多态查询将获取属于该基类的所有子类。 您甚至可以查询不属于 JPA 实体继承模型的接口(interface)或基类。
附言另见 this文档的一部分。
关于java - Hibernate 中的隐式多态与显式多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64601358/