Jpa @CollectionTable very slow query

I have this entity

@Entity
@Table(name = "GEO_MUNICIPALITY", indexes = {
        @Index(name = "idx_municipalityentity", columnList = "PROVINCE_CODE")
})
...
public class MunicipalityEntity {
    @Id
    @Column(name = "MUNICIPALITY_CODE", nullable = false)
    private String code;

    @Column(nullable = false)
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PROVINCE_CODE")
    private ProvinceEntity province;

    @ElementCollection
    @CollectionTable(name = "GEO_MUNICIPALITY_POSTAL_CODE",
            joinColumns = @JoinColumn(name = "MUNICIPALITY_CODE"),
    indexes = {
            @Index(name = "idx_municipalityentity_postal_code", columnList = "MUNICIPALITY_CODE")
    })
    @Column(name = "POSTAL_CODE")
    private List<String> postalCodeList;
}
@Entity
@Table(name = "GEO_PROVINCE")
...
public class ProvinceEntity {
    @Id
    @Column(nullable = false)
    private String code;
...
}

Now my apis need to display all municipalities (with all municipality postal codes) with a given province code, so i have a repository class like this:

@Repository
public interface MunicipalityJpaRepository extends JpaRepository<MunicipalityEntity, String> {
    List<MunicipalityEntity> findAllByProvinceCode(String province);

    @Query("select m from MunicipalityEntity m left join m.postalCodeList postalCodeList where m.province.code = ?1")
    List<MunicipalityEntity> findByCode(String code);
}

The two methods do the same thing and I tried in both way (an the result is the same) because when i call getPostalCodeList() the query is very slow because it make a select for every result of municipality (to retrive the postal codes).

How can I improve the performances? Also, since I always search municipalities by code, is a good idea to make the index like in the code? Thank you!

I tried both using jpa repository and custom query. I was expecting a fast query execution time but the execution is very slow because after the join query the application make a query for each resulted municipality, to fetch the postal codes.



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Object oriented programming concepts (OOPs)

Network Error and Timeout on Authorize.net JS