Working With a Key-Value DataSource in Spring

We want to begin using a SiteOptions properties class in our NixMash Spring app where the properties are stored as Key-Value records in a database table and accessed with siteOptions.getSiteName(), siteOptions.getSiteDescription(), etc. It will function similarly to the wp_options table if you're familiar with the WordPress data schema.

Here's our site_options table.

As you see below we have a simple Entity Model representing our site_options table.

The focus of this post is on how we populate our SiteOptions class properties with the Key-Value data, with each key representing the property name. The really interesting part is that the values can be of any type. For Site Option properties we probably won't need any types other than Strings, Booleans and Integers.

A quick look at our SiteOptions Spring Bean class so you know where we're heading.

We placed all of the logic in a @Test class for now so let's go there. We'll retrieve our SiteOption Key-Value Collection from the repository and confirm it's not null (1). Next we'll create a Hashtable from our <String,Object> Key-Value data (2). Before populating our SiteOption class properties we confirm that its properties are null.

We next iterate over our Hashtable keys and check for matches in the Class Properties. When a match is found we set the property's value with Apache Commons BeanUtils in setSiteOptionProperty(). (3) We'll look at that in detail next.

Lastly in (4) we confirm our properties are populated with the values we loaded in our H2 @Test data script.

Populating the Properties with Apache PropertyUtils

Here's our setSiteOptionsProperty() method. We retrieve the SiteOption Class Property Descriptor with Apache PropertyUtils and check on its Type. We have to do this because there is no Type Casting when setting properties in PropertyUtils. (Not that I've found, anyway.)

We'll cover how we design SiteOption property creation and access in our actual application next.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.

Posted May 09, 2016 03:32 PM EDT

More Like This Post