diff --git a/active-record/README.md b/active-record/README.md new file mode 100644 index 000000000000..5fc2159e9e4e --- /dev/null +++ b/active-record/README.md @@ -0,0 +1,277 @@ +--- +title: "Active Record Pattern in Java: A straightforward coupling of object design to database design" +shortTitle: Active Record +description: "Learn how the Active Record design pattern in Java simplifies data access and abstraction by coupling of object design to database design. Ideal for Java developers seeking a quick solution to data management in smaller-scale applications." +category: Architectural +language: en +tag: + - Data access + - Decoupling + - Persistence +--- + + +## Intent of Active Record Design Pattern + +The Active Record design pattern encapsulates database access within an object that represents a row in a database table or view. + +This pattern simplifies data management by coupling object design directly to database design, making it ideal for smaller-scale applications. + + +## Detailed Explanation of Active Record Pattern with Real-World Examples + +Real-world example + +> Imagine managing an online store and having each product stored as a row inside a spreadsheet; unlike a typical spreadsheet, using the active record pattern not only lets you add information about the products on each row (such as pricing, quantity etc.), but also allows you to attach to each of these products capabilities over themselves, such as updating their quantity or their price and even properties over the whole spreadsheet, such as finding a different product by its ID. + +In plain words + +> The Active Record pattern enables each row to have certain capabilities over itself, not just store data. Active Record combines data and behavior, making it easier for developers to manage database records in an object-oriented way. + +Wikipedia says + +> In software engineering, the active record pattern is an architectural pattern. It is found in software that stores in-memory object data in relational databases. The interface of an object conforming to this pattern would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table. + +## Programmatic Example of Active Record Pattern in Java + +Let's first look at the user entity that we need to persist. + + +```java + +public class User { + + private Integer id; + private String name; + private String email; + + public User(Integer id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + public Integer getId() { + return id; + } + public String getName() { + return name; + } + public String getEmail() { + return email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } +} +``` + +For convenience, we are storing the database configuration logic inside the same User class: + +```java + + private static final String DB_URL = "jdbc:sqlite:database.db"; + + // Establish a database connection. + + private static Connection connect() throws SQLException { + return DriverManager.getConnection(DB_URL); + } + + // Initialize the table (if not exists). + + public static void initializeTable() throws SQLException { + String sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)"; + try (Connection conn = connect(); + Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } + } +``` + +After configuring the database, our User class will contain methods thar mimic the typical CRUD operations performed on a database entry: + +```java + +/** + * Insert a new record into the database. + */ + +public void save() throws SQLException { + String sql; + if (this.id == null) { // New record + sql = "INSERT INTO users(name, email) VALUES(?, ?)"; + } else { // Update existing record + sql = "UPDATE users SET name = ?, email = ? WHERE id = ?"; + } + try (Connection conn = connect(); + PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + pstmt.setString(1, this.name); + pstmt.setString(2, this.email); + if (this.id != null) { + pstmt.setInt(3, this.id); + } + pstmt.executeUpdate(); + if (this.id == null) { + try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) { + if (generatedKeys.next()) { + this.id = generatedKeys.getInt(1); + } + } + } + } +} + +/** + * Find a user by ID. + */ + +public static User findById(int id) throws SQLException { + String sql = "SELECT * FROM users WHERE id = ?"; + try (Connection conn = connect(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, id); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { + return new User(rs.getInt("id"), rs.getString("name"), rs.getString("email")); + } + } + return null; +} +/** + * Get all users. + */ + +public static List findAll() throws SQLException { + String sql = "SELECT * FROM users"; + List users = new ArrayList<>(); + try (Connection conn = connect(); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(sql)) { + while (rs.next()) { + users.add(new User(rs.getInt("id"), rs.getString("name"), rs.getString("email"))); + } + } + return users; +} + +/** + * Delete the user from the database. + */ + +public void delete() throws SQLException { + if (this.id == null) { + return; + } + + String sql = "DELETE FROM users WHERE id = ?"; + try (Connection conn = connect(); + PreparedStatement pstmt = conn.prepareStatement(sql)) { + pstmt.setInt(1, this.id); + pstmt.executeUpdate(); + this.id = null; + } +} +``` + +Finally, here is the Active Record Pattern in action: + +```java +public static void main(final String[] args) { + try { + // Initialize the database and create the users table if it doesn't exist + User.initializeTable(); + LOGGER.info("Database and table initialized."); + + // Create a new user and save it to the database + User user1 = new User(null, "John Doe", "john.doe@example.com"); + user1.save(); + LOGGER.info("New user saved: {} with ID {}", user1.getName(), user1.getId()); + + // Retrieve and display the user by ID + User foundUser = User.findById(user1.getId()); + if (foundUser != null) { + LOGGER.info("User found: {} with email {}", foundUser.getName(), foundUser.getEmail()); + } else { + LOGGER.info("User not found."); + } + + // Update the user’s details + assert foundUser != null; + foundUser.setName("John Updated"); + foundUser.setEmail("john.updated@example.com"); + foundUser.save(); + LOGGER.info("User updated: {} with email {}", foundUser.getName(), foundUser.getEmail()); + + // Retrieve all users + List users = User.findAll(); + LOGGER.info("All users in the database:"); + for (User user : users) { + LOGGER.info("ID: {}, Name: {}, Email: {}", user.getId(), user.getName(), user.getEmail()); + } + + // Delete the user + try { + LOGGER.info("Deleting user with ID: {}", foundUser.getId()); + foundUser.delete(); + LOGGER.info("User successfully deleted!"); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + + } catch (SQLException e) { + LOGGER.error("SQL error: {}", e.getMessage(), e); + } +} +``` + +The program outputs: + +``` +19:34:53.731 [main] INFO com.iluwatar.activerecord.App -- Database and table initialized. +19:34:53.755 [main] INFO com.iluwatar.activerecord.App -- New user saved: John Doe with ID 1 +19:34:53.759 [main] INFO com.iluwatar.activerecord.App -- User found: John Doe with email john.doe@example.com +19:34:53.762 [main] INFO com.iluwatar.activerecord.App -- User updated: John Updated with email john.updated@example.com +19:34:53.764 [main] INFO com.iluwatar.activerecord.App -- All users in the database: +19:34:53.764 [main] INFO com.iluwatar.activerecord.App -- ID: 1, Name: John Updated, Email: john.updated@example.com +19:34:53.764 [main] INFO com.iluwatar.activerecord.App -- Deleting user with ID: 1 +19:34:53.768 [main] INFO com.iluwatar.activerecord.App -- User successfully deleted! +``` + +## When to Use the Active Record Pattern in Java + +Use the Active Record pattern in Java when + +* You need to simplify database interactions in an object-oriented way +* You want to reduce boilerplate code for basic database operations +* The database schema is relatively simple and relationships between tables are simple (like one-to-many or many-to-one relationships) +* Your app needs to fetch, manipulate, and save records frequently in a way that matches closely with the application's main logic + +## Active Record Pattern Java Tutorials + +* [A Beginner's Guide to Active Record](https://dev.to/jjpark987/a-beginners-guide-to-active-record-pnf) +* [Overview of the Active Record Pattern](https://blog.savetchuk.com/overview-of-the-active-record-pattern) + +## Benefits and Trade-offs of Active Record Pattern + +The active record pattern can a feasible choice for smaller-scale applications involving CRUD operations or prototyping quick database solutions. It is also a good pattern to transition to when dealing with the Transaction Script pattern. + +On the other hand, it can bring about drawbacks regarding the risk of tight coupling, the lack of separation of concerns and performance constraints if working with large amounts of data, cases in which the Data Mapper pattern may be a more reliable option. + +## Related Java Design Patterns + +* [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Data Mapper pattern separates database logic entirely from business entities, promoting loose coupling. +* [Transaction Script](https://martinfowler.com/eaaCatalog/transactionScript.html/): Transaction Script focuses on procedural logic, organizing each transaction as a distinct script to handle business operations directly without embedding them in objects. + + +## References and Credits + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) +* [Effective Java](https://amzn.to/4cGk2Jz) +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) +* [J2EE Design Patterns](https://amzn.to/4dpzgmx) +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) diff --git a/active-record/database.db b/active-record/database.db new file mode 100644 index 000000000000..831ad85866ff Binary files /dev/null and b/active-record/database.db differ diff --git a/active-record/etc/active-record.urm.png b/active-record/etc/active-record.urm.png new file mode 100644 index 000000000000..db30fb5d5883 Binary files /dev/null and b/active-record/etc/active-record.urm.png differ diff --git a/active-record/etc/active-record.urm.puml b/active-record/etc/active-record.urm.puml new file mode 100644 index 000000000000..bbff898fa1b6 --- /dev/null +++ b/active-record/etc/active-record.urm.puml @@ -0,0 +1,27 @@ +@startuml +package com.iluwatar.activerecord { + class App { + - LOGGER : Logger {static} + - App() + + main(args : String[]) {static} + } + class User { + - DB_URL : String {static} + - email : String + - id : Integer + - name : String + + User(id : Integer, name : String, email : String) + - connect() : Connection {static} + + delete() + + findAll() : List {static} + + findById(id : int) : User {static} + + getEmail() : String + + getId() : Integer + + getName() : String + + initializeTable() {static} + + save() + + setEmail(email : String) + + setName(name : String) + } +} +@enduml \ No newline at end of file diff --git a/active-record/pom.xml b/active-record/pom.xml index 7b2b0aa2b330..5efadafc693e 100644 --- a/active-record/pom.xml +++ b/active-record/pom.xml @@ -1,4 +1,30 @@ + @@ -8,10 +34,14 @@ java-design-patterns 1.26.0-SNAPSHOT - active-record - + + org.projectlombok + lombok + + 1.18.30 + org.junit.jupiter junit-jupiter-engine diff --git a/active-record/src/main/java/com/iluwatar/activerecord/App.java b/active-record/src/main/java/com/iluwatar/activerecord/App.java index 2e393bedca60..35f49a974925 100644 --- a/active-record/src/main/java/com/iluwatar/activerecord/App.java +++ b/active-record/src/main/java/com/iluwatar/activerecord/App.java @@ -1,7 +1,5 @@ /* - * This project is licensed under the MIT license. - * Module model-view-viewmodel is using ZK framework - * licensed under LGPL (see lgpl-3.0.txt). + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä @@ -24,11 +22,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - package com.iluwatar.activerecord; -import lombok.extern.slf4j.Slf4j; import java.sql.SQLException; import java.util.List; +import lombok.extern.slf4j.Slf4j; /** * The Active Record pattern is an architectural pattern that simplifies @@ -56,27 +53,23 @@ private App() { * * @param args the command line arguments - not used */ - - public static void main(final String[] args) { try { // Initialize the database and create the users table if it doesn't exist User.initializeTable(); - System.out.println("Database and table initialized."); + LOGGER.info("Database and table initialized."); // Create a new user and save it to the database User user1 = new User(null, "John Doe", "john.doe@example.com"); user1.save(); - System.out.println("New user saved: " + user1.getName() - + " with ID " + user1.getId()); + LOGGER.info("New user saved: {} with ID {}", user1.getName(), user1.getId()); // Retrieve and display the user by ID User foundUser = User.findById(user1.getId()); if (foundUser != null) { - System.out.println("User found: " + foundUser.getName() - + " with email " + foundUser.getEmail()); + LOGGER.info("User found: {} with email {}", foundUser.getName(), foundUser.getEmail()); } else { - System.out.println("User not found."); + LOGGER.info("User not found."); } // Update the user’s details @@ -84,29 +77,26 @@ public static void main(final String[] args) { foundUser.setName("John Updated"); foundUser.setEmail("john.updated@example.com"); foundUser.save(); - System.out.println("User updated: " + foundUser.getName() - + " with email " + foundUser.getEmail()); + LOGGER.info("User updated: {} with email {}", foundUser.getName(), foundUser.getEmail()); // Retrieve all users List users = User.findAll(); - System.out.println("All users in the database:"); + LOGGER.info("All users in the database:"); for (User user : users) { - System.out.println("ID: " + user.getId() - + ", Name: " + user.getName() - + ", Email: " + user.getEmail()); + LOGGER.info("ID: {}, Name: {}, Email: {}", user.getId(), user.getName(), user.getEmail()); } // Delete the user try { - System.out.println("Deleting user with ID: " + foundUser.getId()); + LOGGER.info("Deleting user with ID: {}", foundUser.getId()); foundUser.delete(); - System.out.println("User successfully deleted!"); + LOGGER.info("User successfully deleted!"); } catch (Exception e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage(), e); } } catch (SQLException e) { - System.err.println("SQL error: " + e.getMessage()); + LOGGER.error("SQL error: {}", e.getMessage(), e); } } -} +} \ No newline at end of file diff --git a/active-record/src/main/java/com/iluwatar/activerecord/User.java b/active-record/src/main/java/com/iluwatar/activerecord/User.java index 2684feb9e5b6..795b688eccf4 100644 --- a/active-record/src/main/java/com/iluwatar/activerecord/User.java +++ b/active-record/src/main/java/com/iluwatar/activerecord/User.java @@ -1,3 +1,27 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ package com.iluwatar.activerecord; import java.sql.Connection; @@ -9,28 +33,56 @@ import java.util.ArrayList; import java.util.List; +/** + * Implementation of active record pattern. + */ + public class User { + /** + * DB_URL. + */ + private static final String DB_URL = "jdbc:sqlite:database.db"; + /** + * User ID. + */ private Integer id; + + /** + * User name. + */ private String name; + + /** + * User email. + */ private String email; - public User() { } + /** + * User constructor. + */ public User(Integer id, String name, String email) { this.id = id; this.name = name; this.email = email; } - // Establish a database connection + /** + * Establish a database connection. + */ + private static Connection connect() throws SQLException { return DriverManager.getConnection(DB_URL); } - // Initialize the table (if not exists) + + /** + * Initialize the table (if not exists). + */ + public static void initializeTable() throws SQLException { String sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)"; try (Connection conn = connect(); @@ -39,7 +91,10 @@ public static void initializeTable() throws SQLException { } } - // Insert a new record into the database + /** + * Insert a new record into the database. + */ + public void save() throws SQLException { String sql; if (this.id == null) { // New record @@ -51,7 +106,9 @@ public void save() throws SQLException { PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { pstmt.setString(1, this.name); pstmt.setString(2, this.email); - if (this.id != null) pstmt.setInt(3, this.id); + if (this.id != null) { + pstmt.setInt(3, this.id); + } pstmt.executeUpdate(); if (this.id == null) { try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) { @@ -63,7 +120,10 @@ public void save() throws SQLException { } } - // Find a user by ID + /** + * Find a user by ID. + */ + public static User findById(int id) throws SQLException { String sql = "SELECT * FROM users WHERE id = ?"; try (Connection conn = connect(); @@ -76,8 +136,10 @@ public static User findById(int id) throws SQLException { } return null; } + /** + * Get all users. + */ - // Get all users public static List findAll() throws SQLException { String sql = "SELECT * FROM users"; List users = new ArrayList<>(); @@ -91,9 +153,15 @@ public static List findAll() throws SQLException { return users; } - // Delete the user from the database + /** + * Delete the user from the database. + */ + public void delete() throws SQLException { - if (this.id == null) return; + if (this.id == null) { + return; + } + String sql = "DELETE FROM users WHERE id = ?"; try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) { @@ -103,10 +171,22 @@ public void delete() throws SQLException { } } - // Getters and Setters - public Integer getId() { return id; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } + /** + * Getters and setters. + */ + public Integer getId() { + return id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } } diff --git a/active-record/src/main/java/com/iluwatar/activerecord/package-info.java b/active-record/src/main/java/com/iluwatar/activerecord/package-info.java index 3d8ebdedd113..f2c56eb6db0a 100644 --- a/active-record/src/main/java/com/iluwatar/activerecord/package-info.java +++ b/active-record/src/main/java/com/iluwatar/activerecord/package-info.java @@ -1,7 +1,5 @@ /* - * This project is licensed under the MIT license. - * Module model-view-viewmodel is using - * ZK framework licensed under LGPL (see lgpl-3.0.txt). + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä @@ -24,7 +22,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - /** * Context and problem * Most applications require a way to interact with a database to perform diff --git a/active-record/src/test/java/com/iluwatar/activerecord/UserTest.java b/active-record/src/test/java/com/iluwatar/activerecord/UserTest.java index 96555dfcb749..a5a94af019f2 100644 --- a/active-record/src/test/java/com/iluwatar/activerecord/UserTest.java +++ b/active-record/src/test/java/com/iluwatar/activerecord/UserTest.java @@ -1,3 +1,27 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ package com.iluwatar.activerecord; import org.junit.jupiter.api.*; diff --git a/database.db b/database.db new file mode 100644 index 000000000000..c828abf50816 Binary files /dev/null and b/database.db differ diff --git a/update-header.sh b/update-header.sh index 48da4dcd6125..568d00d52a03 100755 --- a/update-header.sh +++ b/update-header.sh @@ -1,4 +1,29 @@ #!/bin/bash +# +# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). +# +# The MIT License +# Copyright © 2014-2022 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + # Find all README.md files in subdirectories one level deep # and replace "### " with "## " at the beginning of lines