• Fat Cats Boardgame
  • Wicket UI Library
  • About Me

Java and Wicket web development thoughts, tutorials, and tips

roman@coderdreams.com
Coder DreamsCoder Dreams
  • Fat Cats Boardgame
  • Wicket UI Library
  • About Me

How to add a data access layer to your Wicket app using Hibernate and Spring JPA with minimal code

December 17, 2019 Posted by Roman Sery database, wicket No Comments

When creating Wicket apps (or any web apps), one of the first things you usually want to do is interact with your database. There’s many different ways to do this, but here we will look at one approach that will get you going in 10 minutes with very little code.

In this example we will be using:

  • MySQL as our database
  • Hibernate as our ORM
  • HikariCP for connection pooling
  • Spring Data JPA for our data access layer (repositories) and transaction management

Add a Configuration class

The first step is to create a “Spring-Boot” style configuration class which will take care of setting up the database connection, pooling, and transaction management:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = DaoPackage.class)
public class AppConfig {
    private static String[] packagesToScan = new String[] {BaseEntity.class.getPackageName()};

    @Primary
    @Bean
    public DataSource dataSource() {
        HikariConfig cfg = new HikariConfig();
        cfg.setJdbcUrl(Utils.getVariable("JDBC_CONNECTION_STRING"));
        cfg.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return new HikariDataSource(cfg);
    }

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan(packagesToScan);
        return entityManagerFactoryBean;

    }

    @Primary
    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }
}

There are several things to note above:

  • You don’t need to call or execute AppConfig yourself. Because it’s annotated with @Configuration, Spring will automatically create the three beans defined in the class.
  • packagesToScan on line 5 is referring to the package where your Hibernate entity classes will be.
  • On line 11, JDBC_CONNECTION_STRING is the name of the environment variable where you will pass your connection string.
  • The @EnableJpaRepositories annotation will enable the data repositories that we discuss in the next section.  It needs to know the package name where the repositories are defined to configure them.

Add your Hibernate entities and Repository

The next and last step is to create our Hibernate entities corresponding to our database tables and their associated repositories. A Spring repository is just a class that contains methods for querying a specific Hibernate entity.

I will assume we know how to create Hibernate entities, so what about repositories? Using Spring data creating them is very simple:

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

}

That’s it! This interface will now allow us to query Users and because we extend JpaRepository, we get plenty of convenience methods included. Let’s look at how we could use it inside of our Wicket pages:

@SpringBean private UserRepository userRepository;
...
List<User> allUsers = userRepository.findAll();        
Optional<User> u = userRepository.findById(15);

We can add custom queries into our repository as well:

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
    @Query("SELECT u FROM User u where u.email = :email")
    Optional<User> findByEmail(@Param("email") String email);
}

Conclusion

From experience, this is one of the quickest ways, with the least amount of code, to create your data access layer. I’m curious how it can be simplified further.

If you have any trouble setting this up, refer to the full working source code on GitHub.

No Comments
Share
2

About Roman Sery

I've been a software developer for over 10 years and still loving Java!

You also might be interested in

Basics of Wicket AJAX requests

Oct 17, 2019

Wicket is a very server-side focused framework, so working with ajax requests is quite different from what you might be used. This will show you how to get started quickly!

How to write a JSON response in Wicket

Jan 26, 2020

Learn how to create JSON response endpoints in Wicket

Reducing Wicket page size part 2: AttributeModifier and AttributeAppender

Sep 22, 2019

Reducing Wicket page size is one of the most important things you can do for performance. In part 2, learn how and when to replace AttributeModifier and AttributeAppender by overriding onComponentTag to squeeze out maxiumum perfomance!

Categories

  • aws
  • customization
  • database
  • debugging
  • enum
  • java
  • models
  • performance
  • projects
  • react
  • software design
  • Spring
  • tool
  • Uncategorized
  • wicket

Recent Posts

  • Rent Day
  • Self-contained Wicket Fragments
  • Pros and cons of unit testing
  • Themeable React Monopoly board
  • Please dont use client-specific release branches

Recent Comments

  • TCI Express Thanks for sharing such insightful information. TCI Express truly stands out as the best air logistics company, offering fast, secure, and efficient air express and cold chain transportation services....

    Tracking down a bug in production Wicket application ·  March 25, 2025

  • Tom Error: A zip file cannot include itself Can you please correct the plugin part so it doesn't use the same folder as input?

    Deploying Spring Boot app to AWS Beanstalk with Nginx customization ·  September 3, 2021

  • Golfman: Reality always wins I've used both Wicket and front-end JS frameworks and, having worked extensively on both, I can tell you that "Speed of development" is definitely NOT with the JS frameworks. You basically end up...

    Five reasons you should use Apache Wicket ·  August 29, 2021

  • Kiriller Sorry can not agree with you, wicket might be a well built technical framework. But the advantages of using a front-end framework like react.js and vue.js can not be beaten by Wicket nowadays. - Speed...

    Five reasons you should use Apache Wicket ·  August 23, 2021

  • Bernd Lauert Sorry but i have to refute your claims with the following arguments: 1. the Wicket community may be small but it is also very responsive, you usually get a helpful answer from the core devs on the...

    Five reasons you should use Apache Wicket ·  July 1, 2021

Archives

  • May 2021
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019

Contact Me

Send Message
Prev Next