简体   繁体   中英

Behavior of Hibernate get vs load with discriminator

I am wondering why hibernate "get" and "load" behave differently concerning discriminated entities?

Mapping:

@Entity
@Table(name = "person")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "type")
public abstract class BasePerson {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected Integer id;

    @Column(name = "name")
    private String name;
    ...
@Entity
@DiscriminatorValue("COMPANY")
public class Company extends BasePerson {

    ...
@Entity
@DiscriminatorValue("CITIZEN")
public class Citizen extends BasePerson {

    ...

The following call returns the specific sub entity (either Company or Citizen):

(BasePerson) hibernateTemplate.getSessionFactory().getCurrentSession().get(BasePerson.class, id);

The following call returns only the super entity BasePerson:

(BasePerson) hibernateTemplate.getSessionFactory().getCurrentSession().load(BasePerson.class, id);

Why is this like that? How can I use load() but get the specific implementation (Citizen or Company object)?

This is because load() doesn't trigger a SELECT statement. It just creates a proxy for the class that you passed with an ID that you passed. Later when you call a method on that proxy - Hibernate will SELECT data from DB. But at that time it can't change the class of an already existing object, so you'll always work with the super class in such case.

In practice this situation usually happens if somewhere in your entities you reference the super class of a hierarchy with lazy OTM or OTO relationship. Since the field is lazy, ORM will also will create a proxy of whatever class it knows (in this scenario it's the super class).

PS: load() can return an entity instead of a proxy, but only if such entity was already loaded by some other code and it already resides within the Session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM