To store properties values in a database and re-utilize them
for future use in Java, you can follow a systematic approach that involves
saving the properties in a relational database, loading them when needed, and
caching them for quick access. Below is a step-by-step guide on how to achieve
this:
1. Define the Properties Table in the Database
First, you need to create a table in the database to store
the properties. Each property will have a key and a value, and you can
optionally include other metadata.
Example SQL Table Structure
sql
CREATE TABLE
properties ( id INT AUTO_INCREMENT PRIMARY KEY, property_key VARCHAR(255) UNIQUE NOT
NULL, property_value VARCHAR(255) NOT NULL, description VARCHAR(255), created_at TIMESTAMP DEFAULT
CURRENT_TIMESTAMP ); |
2. Store Properties in the Database
You can store the properties in the database using JDBC in
Java. Here's how to do it:
Example Code to Store Properties in the Database
java
import
java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.SQLException; import
java.util.Properties; public class
PropertiesDatabase { private static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database"; private static final String USER =
"username"; private static final String PASS =
"password"; public void storeProperties(Properties
properties) { String insertSQL = "INSERT INTO
properties (property_key, property_value) VALUES (?, ?) " + "ON DUPLICATE KEY
UPDATE property_value = VALUES(property_value)"; try (Connection connection =
DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement
preparedStatement = connection.prepareStatement(insertSQL)) { for (String key :
properties.stringPropertyNames()) {
preparedStatement.setString(1, key);
preparedStatement.setString(2, properties.getProperty(key));
preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } } } |
3. Load Properties from the Database
When your application starts or when the properties are
needed, you can load them from the database into a Properties object or a cache
for quick access.
Example Code to Load Properties from the Database
java
import
java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.ResultSet; import
java.sql.SQLException; import
java.util.Properties; public class
PropertiesDatabase { private static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database"; private static final String USER =
"username"; private static final String PASS =
"password"; public Properties loadProperties() { Properties properties = new
Properties(); String querySQL = "SELECT
property_key, property_value FROM properties"; try (Connection connection =
DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement
preparedStatement = connection.prepareStatement(querySQL); ResultSet resultSet =
preparedStatement.executeQuery()) { while (resultSet.next()) { String key =
resultSet.getString("property_key"); String value =
resultSet.getString("property_value"); properties.setProperty(key,
value); } } catch (SQLException e) { e.printStackTrace(); } return properties; } } |
4. Cache or Re-Utilize the Properties
To make the properties easily accessible and re-utilizable
throughout your application, you can cache them in memory using a Map, a Properties
object, or a more sophisticated caching mechanism like Ehcache or Redis.
Example of a Simple In-Memory Cache
java
import
java.util.HashMap; import
java.util.Map; import
java.util.Properties; public class
PropertiesCache { private final Map<String, String>
cache = new HashMap<>(); public void loadToCache(Properties properties) { for (String key :
properties.stringPropertyNames()) { cache.put(key,
properties.getProperty(key)); } } public String getProperty(String key) { return cache.get(key); } public void updateCache(String key,
String value) { cache.put(key, value); } public void clearCache() { cache.clear(); } } |
Or another Java
import
java.util.HashMap; import
java.util.Map; import
java.util.Map.Entry; import
java.util.Properties; /** * * @author kmandal * */ public class
PropertiesReader { private static Map<String,String>
propertiesCache = new HashMap<String,String>(); /** * Injects properties from *.properties(one
or more files) from spring framework. * @param properties */ public void
setProperties(Properties...properties) { if(properties != null &&
properties.length > 0) { for (Properties property : properties) { for (Entry<Object, Object> entry :
property.entrySet()) {
propertiesCache.put((String)entry.getKey(), (String)entry.getValue()); } } } } /** * Gets property value for a given key. * @param keyName * @return */ public static String getPropertyByKey(final
String keyName) { return propertiesCache.get(keyName); } /** * Replaces {} with value. * @param keyName * @param replaceBraces * @return */ public static String getPropertyByKey(final
String keyName, String...replaceBraces) { String sPropValue =
getPropertyByKey(keyName); if(sPropValue != null &&
sPropValue.contains("{}")) { if (replaceBraces != null &&
replaceBraces.length > 0) { for (String replaceBrace : replaceBraces)
{ sPropValue =
sPropValue.replace("{}", replaceBrace); } } } System.out.println("****Key :
"+keyName+", value : "+sPropValue); return sPropValue; } } |
5. Re-Utilize Properties in the Application
Now that the properties are loaded into memory, you can
easily retrieve them whenever needed:
Example Usage
java
public class
Main { public static void main(String[] args) { // Step 1: Load properties from the
database PropertiesDatabase propertiesDatabase
= new PropertiesDatabase(); Properties loadedProperties =
propertiesDatabase.loadProperties(); // Step 2: Load properties into cache PropertiesCache propertiesCache = new
PropertiesCache();
propertiesCache.loadToCache(loadedProperties); // Step 3: Access properties from the
cache String appName =
propertiesCache.getProperty("app.name"); System.out.println("App Name:
" + appName); // Step 4: Update a property
propertiesCache.updateCache("app.version",
"1.1.0"); // Step 5: Clear the cache if needed propertiesCache.clearCache(); } } |
6. Update Properties
If you need to update the properties, you can update the
database and refresh the cache.
Example Code to Update a Property
java
public void
updateProperty(String key, String value) { String updateSQL = "UPDATE
properties SET property_value = ? WHERE property_key = ?"; try (Connection connection =
DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement preparedStatement
= connection.prepareStatement(updateSQL)) { preparedStatement.setString(1,
value); preparedStatement.setString(2, key); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } |
7. Automatically Refresh Cache
You can enhance the application by implementing a mechanism
to automatically refresh the cache when properties change, such as using a
scheduled task or a trigger in the database that notifies the application.
Summary
- Store
Properties: Use JDBC to store properties in a relational database.
- Load
Properties: Load properties from the database into a Properties
object.
- Cache
Properties: Store the properties in memory for quick access using a Map
or a more advanced caching framework.
- Re-Utilize
Properties: Access the properties from the cache throughout your
application.
- Update
Properties: Modify properties in the database and refresh the cache as
needed.
This approach ensures that your properties are stored
persistently, can be loaded and reused easily, and are accessible across
different parts of your application.
Approach 2
Storing properties values in a database and converting them
back into a cache in Java involves several steps. Below, I'll guide you through
the process, assuming you want to use a database like MySQL and a caching
solution such as a simple in-memory cache or a more advanced one like Ehcache
or Redis.
1. Define the Properties Structure
You need to decide how to structure your properties in the
database. Typically, a table can be created with columns for the key and value
of each property.
Example SQL Table Structure
sql
CREATE TABLE
properties ( id INT AUTO_INCREMENT PRIMARY KEY, property_key VARCHAR(255) UNIQUE NOT
NULL, property_value VARCHAR(255) NOT NULL ); |
2. Store Properties in the Database
You can store key-value pairs of your properties in the
database using JDBC in Java.
Example Code to Store Properties
java
import
java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.SQLException; import
java.util.Properties; public class
PropertiesDatabase { private static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database"; private static final String USER =
"username"; private static final String PASS =
"password"; public void storeProperties(Properties
properties) { String insertSQL = "INSERT INTO
properties (property_key, property_value) VALUES (?, ?) " + "ON DUPLICATE KEY
UPDATE property_value = VALUES(property_value)"; try (Connection connection =
DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement
preparedStatement = connection.prepareStatement(insertSQL)) { for (String key :
properties.stringPropertyNames()) {
preparedStatement.setString(1, key);
preparedStatement.setString(2, properties.getProperty(key));
preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } } } |
3. Load Properties from Database
To reload the properties from the database into your
application, you'll need to query the database and load the values into a Properties
object or directly into your cache.
Example Code to Load Properties
java
import
java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.ResultSet; import
java.sql.SQLException; import
java.util.Properties; public class
PropertiesDatabase { private static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database"; private static final String USER =
"username"; private static final String PASS =
"password"; public Properties loadProperties() { Properties properties = new
Properties(); String querySQL = "SELECT
property_key, property_value FROM properties"; try (Connection connection =
DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement
preparedStatement = connection.prepareStatement(querySQL); ResultSet resultSet =
preparedStatement.executeQuery()) { while (resultSet.next()) { String key =
resultSet.getString("property_key"); String value =
resultSet.getString("property_value"); properties.setProperty(key,
value); } } catch (SQLException e) { e.printStackTrace(); } return properties; } } |
4. Cache the Loaded Properties
Once the properties are loaded from the database, you can
store them in a cache. If you're using a simple in-memory cache, you can use a Map
or a more advanced caching framework like Ehcache or Redis.
Example of Caching with a Simple Map
java
import
java.util.HashMap; import
java.util.Map; import
java.util.Properties; public class
PropertiesCache { private final Map<String, String>
cache = new HashMap<>(); public void loadToCache(Properties
properties) { for (String key :
properties.stringPropertyNames()) { cache.put(key,
properties.getProperty(key)); } } public String getProperty(String key) { return cache.get(key); } } |
Or another Java
import
java.util.HashMap; import
java.util.Map; import
java.util.Map.Entry; import
java.util.Properties; /** * * @author kmandal * */ public class
PropertiesReader { private static Map<String,String>
propertiesCache = new HashMap<String,String>(); /** * Injects properties from *.properties(one
or more files) from spring framework. * @param properties */ public void
setProperties(Properties...properties) { if(properties != null &&
properties.length > 0) { for (Properties property : properties) { for (Entry<Object, Object> entry :
property.entrySet()) {
propertiesCache.put((String)entry.getKey(), (String)entry.getValue()); } } } } /** * Gets property value for a given key. * @param keyName * @return */ public static String getPropertyByKey(final
String keyName) { return propertiesCache.get(keyName); } /** * Replaces {} with value. * @param keyName * @param replaceBraces * @return */ public static String getPropertyByKey(final
String keyName, String...replaceBraces) { String sPropValue =
getPropertyByKey(keyName); if(sPropValue != null &&
sPropValue.contains("{}")) { if (replaceBraces != null &&
replaceBraces.length > 0) { for (String replaceBrace : replaceBraces)
{ sPropValue =
sPropValue.replace("{}", replaceBrace); } } } System.out.println("****Key :
"+keyName+", value : "+sPropValue); return sPropValue; } } |
Example
of Caching with Ehcache
java
import
org.ehcache.Cache; import
org.ehcache.CacheManager; import
org.ehcache.config.builders.CacheConfigurationBuilder; import
org.ehcache.config.builders.CacheManagerBuilder; import
org.ehcache.config.builders.ResourcePoolsBuilder; public class
PropertiesEhcache { private final Cache<String, String>
cache; public PropertiesEhcache() { CacheManager cacheManager =
CacheManagerBuilder.newCacheManagerBuilder().build(); cacheManager.init(); cache =
cacheManager.createCache("propertiesCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class,
String.class,
ResourcePoolsBuilder.heap(100))); } public void loadToCache(Properties
properties) { for (String key :
properties.stringPropertyNames()) { cache.put(key,
properties.getProperty(key)); } } public String getProperty(String key) { return cache.get(key); } } |
5. Usage Example
Here’s how you can use the above classes:
java
public class
Main { public static void main(String[] args) { PropertiesDatabase propertiesDatabase
= new PropertiesDatabase(); // Example: Store properties Properties propertiesToStore = new
Properties();
propertiesToStore.setProperty("app.name",
"MyApp");
propertiesToStore.setProperty("app.version",
"1.0.0");
propertiesDatabase.storeProperties(propertiesToStore); // Example: Load properties from the
database Properties loadedProperties =
propertiesDatabase.loadProperties(); // Example: Load properties into
cache PropertiesCache propertiesCache = new
PropertiesCache();
propertiesCache.loadToCache(loadedProperties); // Example: Access a property from
cache String appName =
propertiesCache.getProperty("app.name"); System.out.println("App Name:
" + appName); } } |
Summary
- Store
properties: Use a Properties object and JDBC to store properties in a
database.
- Load
properties: Load the properties from the database back into a Properties
object.
- Cache
properties: Use a simple in-memory Map or a caching framework like
Ehcache to cache the properties.
- Access
properties: Retrieve properties from the cache as needed.
This approach allows you to manage application
configurations dynamically and ensures that the properties can be reloaded and
cached efficiently.
For More DSA Related information, visit
Ø
Frequency
Weaving Logic & Spiral Printing of a Rectangle
Ø
Zig Zag
Matrix print multiple way
Ø
Greedy
Algorithm’s or knapsack algorithms
Ø
understanding
recursive method for binary tree
Ø
Dynamic
Programming: Max Square Sub-matrix of 1s in a Matrix
Ø
Previous and
Next Date Palindrome
Ø
Karatsuba's
Algorithm for multiplying two large numbers
Ø Bench mark of compiler using Ackerman function
Ø To check if the rows of a matrix are circularly identical in Java
Ø Multiplication In different Way
Ø
Alphanumeric
Random Number generator
Ø
Solving
Tiger-Goat-Boatman Puzzle: BFS & DFS River Crossing
Ø Dijkstra
Shortest Path for directed an undirected graph
Ø Dollar
amount into the minimum number of currency denominations in java
Ø
Learn about Dijkstra’s Algorithm in Java [Click
here]
Ø How to draw a Tree from array of integer
Ø Position of robot after given movements
For More Java Related information, visit
Ø
Streams
Lambdas Collectors and Functional Interfaces in Java 8
Ø
Java
8 support static method or default method or both in the interface
Ø Serialization understanding
Ø
Under
Standing Of Mutable and Immutable Class
0 Comments