简体   繁体   中英

How to optimize Carstesian Product when loading Hibernate Entity

To demonstrate my problem, I created a simple Spring Boot application. It has one Entity, which has ID, two String properties and two Sets<String> sets.

package com.mk.cat.domain;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "cat")
public class Cat {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "sex")
    private String sex;

    @ElementCollection(fetch = FetchType.EAGER)
    @Column(name = "color")
    @CollectionTable(
            name = "cat_color",
            joinColumns = @JoinColumn(name = "cat_id"))
    private Set<String> colors;

    @ElementCollection(fetch = FetchType.EAGER)
    @Column(name = "nickname")
    @CollectionTable(
            name = "cat_nickname",
            joinColumns = @JoinColumn(name = "cat_id"))
    private Set<String> nicknames;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Set<String> getColors() {
        return colors;
    }

    public void setColors(Set<String> colors) {
        this.colors = colors;
    }

    public Set<String> getNicknames() {
        return nicknames;
    }

    public void setNicknames(Set<String> nicknames) {
        this.nicknames = nicknames;
    }
}

There is also a simple code, which persists and loads the Cat Entity from DB.

package com.mk.cat;

import com.google.common.collect.Sets;
import com.mk.cat.domain.Cat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CatApplication implements CommandLineRunner {

    private final CatRepository catRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(CatApplication.class);

    @Autowired
    public CatApplication(CatRepository catRepository) {
        this.catRepository = catRepository;
    }

    public static void main(String[] args) {
        SpringApplication.run(CatApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Cat cat = new Cat();
        cat.setName("Ben");
        cat.setSex("Male");
        cat.setNicknames(Sets.newHashSet("Fluffy", "Mr. Tomcat", "Catburger"));
        cat.setColors(Sets.newHashSet("Black", "White"));

        final Cat saved = catRepository.save(cat);
        LOGGER.info("Cat saved={}", cat);

        catRepository.findOne(saved.getId());
    }
}

I traced Hibernate and I found, that the Cat is loaded from DB by this SQL.

select cat0_.id as id1_0_0_, 
    cat0_.name as name2_0_0_,
    cat0_.sex as sex3_0_0_,
    colors1_.cat_id as cat_id1_1_1_, 
    colors1_.color as color2_1_1_, 
    nicknames2_.cat_id as cat_id1_2_2_, 
    nicknames2_.nickname as nickname2_2_2_
  from cat cat0_ 
  left outer join cat_color colors1_ on cat0_.id=colors1_.cat_id 
  left outer join cat_nickname nicknames2_ on cat0_.id=nicknames2_.cat_id 
where cat0_.id=1

The Hibernate then gets this Cartesian product from the rows of the cat table and two tables, that represent the Cat#colors and Cat#nicknames sets.

id1_0_0_    name2_0_0_  sex3_0_0_   cat_id1_1_1_    color2_1_1_ cat_id1_2_2_    nickname2_2_2_
1   Ben Male    1   Black   1   Fluffy
1   Ben Male    1   Black   1   Catburger
1   Ben Male    1   Black   1   Mr. Tomcat
1   Ben Male    1   White   1   Fluffy
1   Ben Male    1   White   1   Catburger
1   Ben Male    1   White   1   Mr. Tomcat

Hibernate then goes through each and every line, parses every single item of the ResultSet and creates the Entity. Is it somehow possible to optimize this approach? I would like to select the Cat#colors and Cat#nicknames sets by a subselect, due to serious performance problems. In the real case, I fetch 1500 Entities, that have complex structure and it is not uncommon, that one fetched Entity generates 25.000 rows in the corresponding ResultSet causing a very long parsing time.

The lazy loading in my case is not the option I would like to use, because it brings clutter to the code. As far as I know, the lazily loaded Collection must be initialized by first call and this is quite a big usability price to pay in my real application.

I would appreciate 3 separate selects, one from the cat table, one from the cat_color table and one from the cat_nickname table.

I found the solution for Hibernate, the @Fetch(FetchMode.SELECT) did the work, because it made Hibernate to select the nicknames by a separate select instead of join.

@Fetch(FetchMode.SELECT)
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "nickname")
@CollectionTable(
        name = "cat_nickname",
        joinColumns = @JoinColumn(name = "cat_id"))
private Set<String> nicknames;

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