0

I'm working on some personal project but i have a question about hibernate.

I have a class structure like this :

@Entity
public class User {


    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "fkIdCompanyUser")
    private Company company = new Company();

}

But inside the company i have another join.

@Entity
public class Company {

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "fkIdCompanyEstimateOption")
    private EstimateOptions estimateOptions = new EstimateOptions();

}

Now i do a query to get the estimate options. But if i do it like this it loads lots of unnecessary stuff .

@RequestMapping(value = "/estimateoptions")
public EstimateOptions getCompanyEstimateOptions(@AuthenticationPrincipal Principal user) {

    User getuser = userDao.findByEmail(user.getName());

    EstimateOptions estimateOptions = getuser.getCompany().getEstimateOptions();

    return estimateOptions;
}

is there a better approach for this ?

Greg
  • 1,690
  • 4
  • 26
  • 52

1 Answers1

1

There are a lot of ways to do such optimization. The simplest one is add bidirectional associations to Company and EstimateOptions with lazy loading. An example for Company ( I don't test. It is just a sketch.)

@Entity
public class Company {

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "fkIdCompanyEstimateOption")
    private EstimateOptions estimateOptions = new EstimateOptions();

    @OneToOne(mappedBy="company", fetch = FetchType.LAZY)
    private User user; 

}

And do something like this (this is HQL but you can use a criteria API too)

from EstimateOptions options inner join options.company company inner join company.user user where user.name = :userName

You can see HQL joined query to eager fetch a large number of relationships for additional thoughts.

Updated

I am not sure but may be you can do something like this (without additional associations)

select options from User user inner join user.company company inner join company.estimateOptions options where user.name = :userName
Community
  • 1
  • 1
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
  • Hi thanks for this answer but i'm kinda stuck. i keep getting a error This inspection controls whether the Persistence QL Queries are error-checked. I also made a post about this here: http://stackoverflow.com/questions/34178331/intellij-can-not-find-classloadingexception-hql-in-intellij-and-this-inspection – Greg Dec 09 '15 at 12:02
  • It was a bit of a struggle but i got it working thanks to you ;) – Greg Dec 09 '15 at 12:58