简体   繁体   中英

Hibernate entity inheritance. Single table lazy loading

I need to implement entity property lazy loading. I came with single table inheritance approach.

@Entity
@Table(name = "person")
@Getter
public class Person {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @Column(name = "firstname")
    private String firstName;
}

@Entity
@Getter
public class VerbosePerson extends Person {
    @Column(name = "lastname")
    private String lastName;
}

public interface PersonRepository extends JpaRepository<Person, Long> {}
public interface VerbosePersonRepository extends JpaRepository<VerbosePerson, Long> {}

Unfortunately, this only works with a discriminator column. Actually, I don't need to distinguish these two entities. All that requires is to exclude lastName column from the Person fetching and to load it only when VerbosePerson is being requested.

One solution is to declare @MappedSuperClass that should have two inherited entities ( Person and VerbosePerson ). But in this case, Person won't be a supertype for VerbosePerson which is not convenient.

Is there any way to use single table strategy inheritance without discriminators?

It sounds like you need lazy querying and not the inheritance. You should take a look at FetchType annotations

https://thorben-janssen.com/entity-mappings-introduction-jpa-fetchtypes/

Be warned though.. these are primarily used to manage lazy loading for Lists (things that can be easily proxied). Lazily associating a single item (ie a @ManyToOne or a simple string, etc.) usually requires some careful object proxying under the covers to ensure it works the way you think it should in your persistence framework. Generally I didn't use it much but I think I did at one point or another to lazily load a class that had variables mapped to a row of a hibernate object that I lazily loaded..

Check out:

https://thorben-janssen.com/lazy-load-non-relational-attributes/#:~:text=The%20JPA%20specification%20defines%20the,value%20must%20be%20eagerly%20fetched .

Pay special attention to the parts:

practices, that means that depending on your JPA implementation, annotating an attribute with @Basic(fetch=FetchType.LAZY) isn't enough.

Lazy loading for fields requires bytecode enhancement. Then you can use @Basic(fetch = LAZY) and the field will be lazy loaded on first access. Also see https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#BytecodeEnhancement

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