3

Scenario:

I'm supporting an Enterprise application that runs in Wildfly10. The application (.war) uses J2EE technologies (EJBs, JPA, JAX-RS) and SpringBoot features (like, SpringMVC, SpringRest, SpringData, SpringRestData) ... Both stacks co-exists "happily" because they don't interact between them; however, they do share common classes, like utility or Entity Classes (the stacks map to the same database model). Why the application uses those stacks is out the scope of the question.

Currently, I'm trying to improve the performance of a @RestController that pulls some data from the database using a JPA Spring Repository. I found that we're suffering the N + 1 queries problem when calling the @RestController. In past projects (where there were only J2EE technologies), I have used the @BatchSize hibernate annotation to mitigate this problem with total success.

But, in this project, Spring seems to be skipping such annotation. How do I know that? Because I turned on the hibernate SQL logging (hibernate.show_sql) and I can see the N + 1 queries is still happening ...


Key Points:

Here are some insights about the application that you must know before providing (or trying to guess) any answer:

  1. The application has many sub-modules encapsulated as libraries inside WAR file (/WEB-INF/lib) ... Some of these libraries are the jars that encapsulate the entity classes; others are the jars that encapsulate the REST Services (that could be JAX-RS services or Spring Controllers).
  2. The Spring configuration is done in the classes defined in the WAR artifact: in there, we have a class (that extends from SpringBootServletInitializer) annotated with @SpringBootApplication and another class (that extends from RepositoryRestConfigurerAdapter) annotated with @Configuration. Spring customization is done is such class.
  3. The application works with multiple datasources, which are defined in the Wildly server. Spring DATA JPA must address any query pointing to the right datasource. To accomplish this requirement, the application (Spring) was configured like this:

@Bean(destroyMethod="")
@ConfigurationProperties(prefix="app.datasource")
public DataSource dataSource() {
    // the following class extends from AbstractRoutingDataSource
    // and resolve datasources using JNDI names (the wildfly mode!)
    return new DataSourceRouter();
}

@Bean("entityManagerFactory")
public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
    LocalContainerEntityManagerFactoryBean lemfb;

    lemfb = new LocalContainerEntityManagerFactoryBean();

    lemfb.setPersistenceUnitName("abcd-pu");
    lemfb.setDataSource(dataSource());

    return lemfb;
}

The last @Bean declaration favors the use of a persistence.xml file, which we do have in the route /WEB-INF/classes/META-INF/ (i.e. Spring does find this file!) ... In such file, we define our domain classes, so that Spring JPA can see such entities. Also, we can define special JPA properties like: hibernate.show_sql and hibernate.use_sql_comments without issues (this is how I detected the N + 1 queries problem in the first place) ...


What I have done so far?

  1. I tried to add the @BatchSize annotation to the problematic collection. No luck!

  2. I created a new JAX-RS Service whose purpose was to mimic the behavior of the @RestController. I confirmed that the @BatchSize annotation does work in the application's deployment, at least, in JAX-RS Services! (NOTE: the service uses it own persistence.xml) ...

Test details (Updated 2020/07/30): What I did here was to create a new JAX-RS Service and deployed it inside the WAR application, next to the @RestController that presents the problem (I mean, it is the same WAR and the same physical JVM). Both services pull from database the same entity (same class - same classloader), which has a lazy Collection annotated with @BatchSize! ... If I invoke both services, the JAX-RS honors the @BatchSize and pulls the collection using the expected strategy, the @RestController does not ... So, what it is happening here? The only thing different between the services is that each one has a different persistence.xml: the persistence.xml for the JAX-RS is picked by Wildfly directly, the other one is picked by Spring and delegated to Wildfly (I guess) ...

  1. I tried to add the properties: hibernate.batch_fetch_style (=dynamic) and hibernate.default_batch_fetch_size (=10), to the persistence.xml read by Spring ... No luck. I debug the Spring startup process and I saw that such properties are passed to the Spring Engine, but Spring does not care about them. The weird thing here is that properties like: hibernate.show_sql, Spring does honor them ... For those who are asking: "What does these properties do?" Well, they are global equivalent to apply @BatchSize to any JPA lazy collection or proxy without declaring such annotation in any entity.

  2. I setup a small SpringBoot Project using the same Spring version as enterprise application (which is 1.5.8.RELEASE, by the way) and both the annotation and properties approach worked as supposed to.


I've been stuck with this issue for two days, any help to fix this will be appreciated ... thanks!

Carlitos Way
  • 3,279
  • 20
  • 30
  • Nothing to do with datasource config, IMO. Can you share your entity codes? We might be able to help better. – Anand Vaidya Jul 30 '20 at 07:30
  • Spring doesn't do anything with `@BatchSize`, that is hibernate does something with it. Spring doesn't read anything hibernate is. Spring is only a layer over those things to make configuration easier, Spring isn't reading or interpreting anything. – M. Deinum Jul 30 '20 at 07:58
  • I cannot state it enough Spring isn't loading anything, it is delegating to JPA. Now if you shipped JPA inside your application AND within WildFly things get interesting. Again Spring has **nothing** to do with this it is all your and everything with how you use hibernate. – M. Deinum Jul 30 '20 at 15:43
  • What is "N+1 queries problem"? – maksimov Jul 30 '20 at 16:43
  • 1
    @maksimov, you can check this to understand what is the "N+1" queries problem: https://stackoverflow.com/a/49789933 – Carlitos Way Jul 30 '20 at 21:37
  • @CarlitosWay thank you. It's gross, but I suppose bad things are meant to happen to lazy people. – maksimov Jul 31 '20 at 21:09

1 Answers1

0

There are 2-3 possible issues that I can think off.

  1. For some reason, whatever you modify isnt picked up by wildfly - Wildfly classpath resolution is a separate Topic and some missing configuration can cause you a nightmare. This you can identify if you have access to debug the query, and in if you put a breakpoint in the constructor of your Entity class, you will get a chance to evaluate the entity configuration being used, somewhere in the execution conetxt.
  2. BatchSize doesnt work on OneToOne, It only works on OneToMany relationships.
  3. A typical way to define BatchSize is to do along with Lazy load as mentioned in the example here. If you are not using Lazy fetch, hibernate assumes that you are willing to make an eager load and makes another select query to fetch all the details.Please confirm you are using the same syntax as given in the example above.

New Addition:

  1. Put Conditional Breakpoints in PropertyBinder#setLazy() function, and may be backtrace it and put relavent breakpoints in CollectionBinder and AnnotationBinder. then restart/redeploy the server and see what data you are getting for the relavent properties. That will give you fair idea where it is failing..

    • Why conditional breakpoint? Its because you will have thousands of properties and if you do not add condition to the breakpoint, you will take 1 hour to reach your actual breakpoint
    • What should be the condition - If its property binder, the condition shoud be like `this.name == . For other classes also you can use the same approach.

    Sorry for too detailed description on conditional breakpoints, you might find it redundent.

Looks like the only way to debug your problem is to debug hibernate framework from server startup, then only we will be able to find out the rootcause

Anand Vaidya
  • 1,374
  • 11
  • 26
  • Thanks, @Anand Vaidya; maybe I was not explicit enough, but I crossed all listed issues when I did the test #2 described in my question ... I'll update the test description to explain why ... – Carlitos Way Jul 30 '20 at 15:12
  • Is your code copyright protected? Can it be shared by some mean like gitlab repo etc.. the issue seems to be an isolated environment issue, and only debugging is what will help, IMO. – Anand Vaidya Jul 31 '20 at 06:41
  • Did you try putting a breakpoint inside Consttructor and debug from there to find out a root cause? If you are interested, we can have a screenshare session, the problem looks interesting to me.. – Anand Vaidya Jul 31 '20 at 10:45
  • Which constructor specifically? – Carlitos Way Jul 31 '20 at 18:58
  • added to the original answer. – Anand Vaidya Aug 01 '20 at 05:54