Search code examples
javaspringhibernatespring-data-jpadesktop-application

Reducing boilerplate code in Hibernate repositories/using Spring's JpaRepository interface in a desktop client-server application


I'm currently working on a desktop Java client-server application that uses Hibernate to access a database. Many of the calls to the database are generic CRUD operations and so I'd love a way to reduce the amount of boilerplate code.

I've stumbled upon the JpaRepository/CrudRepository interfaces in the Spring Framework and would like to be able to use either of them but it feels as though I'm constantly fighting against Spring's web-application focus. For instance, as repositories are autowired in by Spring, I'm not able to instantiate a copy or make a static instance and so it becomes difficult to call any of the repository's methods from the server class.

As such I have four questions:

  1. Is there a way to use the Spring Jpa/CrudRepository interfaces without autowiring them in?
  2. Is there a way to use either interface without using Spring?
  3. Is there an alternative interface for desktop applications which would achieve the same purpose?
  4. Is there a better alternative that I'm missing?

Solution

  • chrylis gave you the answer that you really need in the comments:

    Make your "program" a Spring component

    I'd say the appropriate way to do that would be to make it a CommandLineRunner

    I'd even go beyond that and say: Even if you start you in a single process you should maintain a web like architecture, possibly even a web server in the application in order to

    a) work with JPA in a reasonable way, i.e. have clearly defined requests that get processed by the server process in separate threads

    b) do not block the UI while queries get processed.

    To answer your literal questions:

    Is there a way to use the Spring Jpa/CrudRepository interfaces without autowiring them in?

    Yes, you can manually create repositories using the JpaRepositoryFactory

    Is there a way to use either interface without using Spring?

    The interfaces themselves are just interfaces and can be used without anything else from Spring. Of course the benefit of that is limited.

    Is there an alternative interface for desktop applications which would achieve the same purpose?

    No, there is no need for that.

    Is there a better alternative that I'm missing.

    I don't think so but I'm biased.