Alex Tbk
Alex Tbk

Reputation: 2104

Spring Boot JPA poor performance

I have a simple entity with two fields

@Entity
@Table(name = "lctn_locations")
public class LocationEntity {

    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;

    @ElementCollection
    @CollectionTable(
            name = "lctn_location_devices",
            joinColumns = @JoinColumn(name = "location_id", referencedColumnName = "id")
    )
    @Column(name = "device_id")
    private Set<UUID> devices = new LinkedHashSet<>();

The lctn_locations table contains 780 entries. The lctn_location_devices table just 11 entries.

I fetch 20 Locations and convert the Entity classes to my DTOs like this:

public Location map(LocationEntity locationEntity) {

     Location location = new Location();
     location.setId(locationEntity.getId());
     long c2 = System.currentTimeMillis();
     Set<UUID> devices = locationEntity.getDevices();
     for(UUID deviceId : devices) {
         location.getDevices().add(deviceId);
     }
     logger.info("Devices in {}ms", System.currentTimeMillis()-c2);

     return location;
}

My issue is that mapping of devices takes ~500ms per location.
Setting the devices field on the Entity to FetchType.EAGER doesnt help much, as then the initial loading from the DB is slower.

The lctn_location_devices has two indexes:

create index location_devices_location_id_device_id
    on lctn_location_devices (location_id, device_id);

create index lctn_location_devices_location_id_index
    on lctn_location_devices (location_id);

I am not experienced enough with JPA, am I doing anything wrong?

Upvotes: 0

Views: 185

Answers (1)

Kaj Hejer
Kaj Hejer

Reputation: 1040

A place to starte might be to log the sql the app sends to the database by adding the following to your application.properties:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true

This will not give you the parameters in the sql, but you might be able to replace the ? in the sql with the relevant values.

Then you can try to run the sql from database tool to see if it is slow then too.

If so, you can try to run explain plan in your database. How do to that can depend on what database you are on. Explain plan will give you some info about which part of your sql which have the highest cost to execute and might give you some info on where to optimize your code.

If you want to look into explain plan you might give a search for explain plan on youtube a shot.

Upvotes: 1

Related Questions