Gerardo
Gerardo

Reputation: 195

Performance improvement at Spring Data JPA model

I'm using Spring Data JPA and Hibernate to model the following scenario:

  1. A User have multiple Topics
  2. A Topic have multiple Property
  3. A User can have multiple CustomProperty for every Topic

The code could be:

@Entity
public class User {
    @Id
    public Long id;
    public String name;
    @OneToMany (mappedBy="user")
    public List<CustomProperty> customProperties;
}

@Entity
public class Topic {
    @Id
    public Long id;
    public String name;
    @OneToMany (mappedBy="topic")
    public List<Property> properties;
}

@Entity
public class Property {
    @Id
    public Long id;
    public String key;
    public String value;
    @ManyToOne
    public Topic topic;
}

@Entity
public class CustomProperty {
    @Id
    public Long id;
    public String key;
    public String value;
    @ManyToOne
    public Topic topic;
    @ManyToOne
    public User user;
}

I need to return a JSON with the list of topics of a user and the properties. The custom properties have to overwrite the topic properties whit the same key.

For example if "topic1" has the properties "keyA": "valueA", "keyB": "valueB" and "keyC": "valueC" and the user "John" has the custom property "keyB": "customValue" for "topic1" the result should be:

[
    {
         "name": "topic1",
         "keyA": "valueA",
         "keyB": "customValue",
         "keyC": "valueC"
    }
]

Everything is working properly, the problem is the performance. The way I generate the JSON is:

  1. Get the list of topics for a user (1 access to DB)
  2. Get the list of properties for ever topic (n access to DB) - n = number of topics
  3. Get the list of custom properties for every topic (n access to DB)
  4. Overwrite the topic properties with the custom ones

Do you think there is some better way to do it? Maybe changing the DB design?

Any suggestion is welcome.

Thank you.

Upvotes: 2

Views: 921

Answers (1)

Neonailol
Neonailol

Reputation: 117

your's current workflow is correct for relational database

if you wish improve performance of lockups and joins you can try some graph databases like neo4j and spring-data-neo4j

also, there is interesting article to read about orm - solving orm complexity

Upvotes: 1

Related Questions