forked from iluwatar/java-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from TwentyVentti/ActiveRecordPattern
Active record pattern
- Loading branch information
Showing
11 changed files
with
810 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,230 @@ | ||
--- | ||
title: Active Record | ||
category: Architectural | ||
language: en | ||
tags: | ||
- Data access | ||
--- | ||
|
||
## Intent | ||
The active record design pattern is a way of accessing data from databases by creating an object which contains the contents of a database row. | ||
|
||
## Explanation | ||
The ActiveRecord object is intitialised by an ActiveDatabase object which creates a connection to an exisitng database. | ||
|
||
Real-world example | ||
> You want to implement an application which access and update a database from within an OOP context. | ||
> Update the database within a program. | ||
In plain words | ||
|
||
> For a system which requires database storage and ability to change its contents too. | ||
Wikipedia says | ||
>The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view. | ||
|
||
**Programmatic Example** | ||
|
||
This implementation shows what the Active Record pattern could look like in a generic context. The Active Record makes initialises `contents` and `columns` as lists of strings. A developer can create an `ActiveDatabase` object by entering the configuration details required to start the connection. Assuming there is an exsiting database the developer would then create an `ActiveRecord` object using the `ActiveDatabase` object and the `id` of the row with which they would like to create in an active context. They are able to locate the row which matches this `id` then this can be read or deleted. | ||
|
||
If you are adding in a new row you can just update the `contents` list which would be empty if created with an `id` which doesnt exist yet. | ||
|
||
```java | ||
public class ActiveRow { | ||
|
||
String id; | ||
ActiveDatabase dataBase; | ||
Connection con; | ||
String read; | ||
String delete; | ||
String write; | ||
int columnCount; | ||
ArrayList<String> columns; | ||
ArrayList<String> contents = new ArrayList<>(); | ||
|
||
/** | ||
* ActiveRow attempts to implement the fundamental ruby on rails 'Active Record' design pattern in | ||
* Java. | ||
* | ||
* @param dataBase A Database object which handles opening the connection. | ||
* @param id The unique identifier of a row. | ||
*/ | ||
public ActiveRow(ActiveDatabase dataBase, String id) { | ||
this.dataBase = dataBase; | ||
this.id = id; | ||
initialise(); | ||
} | ||
|
||
/** | ||
* This initialises the class by creating a connection and populating the column names and other | ||
* variables which are used in the program. | ||
*/ | ||
@Rowverride | ||
public void initialise() { | ||
try { | ||
con = DriverManager | ||
.getConnection("jdbc:mysql://" + dataBase.getDbDomain() + "/" + dataBase.getDbName(), | ||
dataBase.getUsername(), dataBase.getPassword()); | ||
} catch (SQLException e) { | ||
e.printStackTrace(); | ||
} | ||
|
||
try { | ||
Statement statement = con.createStatement(); | ||
ResultSet columnSet = statement.executeQuery( | ||
"SELECT * FROM `" + dataBase.getDbName() + "`.`" + dataBase.getTableName() + "`"); | ||
ArrayList<String> columnNames = new ArrayList<String>(); | ||
ResultSetMetaData rsmd = columnSet.getMetaData(); | ||
columnCount = rsmd.getColumnCount(); | ||
for (int i = 1; i < columnCount + 1; i++) { | ||
String name = rsmd.getColumnName(i); | ||
columnNames.add(name); | ||
} | ||
this.columns = columnNames; | ||
read = | ||
"SELECT * FROM `" + dataBase.getDbName() + "`.`" + dataBase.getTableName() + "` WHERE ID=" | ||
+ this.id; | ||
delete = "DELETE FROM `" + dataBase.getDbName() + "`.`" + dataBase.getTableName() + "`" | ||
+ " WHERE ID = '" + this.id + "';"; | ||
write = "INSERT INTO `" + dataBase.getDbName() + "`.`" + dataBase.getTableName() + "`"; | ||
statement.close(); | ||
columnSet.close(); | ||
} catch (SQLException e) { | ||
e.printStackTrace(); | ||
} | ||
|
||
|
||
} | ||
|
||
/** | ||
* Writes contents of the active row object to the chosen database. | ||
*/ | ||
@Rowverride | ||
public void write() { | ||
StringBuilder query = new StringBuilder(); | ||
query.append(write); | ||
query.append(" VALUES ("); | ||
for (String con : this.contents) { | ||
if (contents.indexOf(con) != this.contents.size() - 1) { | ||
query.append("'").append(con).append("' ,"); | ||
} else { | ||
query.append("'").append(con).append("' )"); | ||
} | ||
} | ||
|
||
try { | ||
PreparedStatement stmt = con.prepareStatement(query.toString()); | ||
stmt.executeUpdate(); | ||
|
||
} catch (Exception e) { | ||
e.printStackTrace(); | ||
} | ||
|
||
} | ||
|
||
/** | ||
* Deletes the current instance of the active row from the database based on the given ID value. | ||
*/ | ||
@Rowverride | ||
public void delete() { | ||
if (this.read().equals(new ArrayList<String>())) { | ||
System.out.println("Row does not exist."); | ||
return; | ||
} | ||
try { | ||
con.prepareStatement(delete).executeUpdate(); | ||
|
||
} catch (Exception e) { | ||
e.printStackTrace(); | ||
} | ||
} | ||
|
||
/** | ||
* Reads the current active row. | ||
* | ||
* @return the current active row contents as Arraylist | ||
*/ | ||
@Rowverride | ||
public ArrayList<String> read() { | ||
try { | ||
Statement statement = con.createStatement(); | ||
|
||
ResultSet rowResult = statement.executeQuery(read); | ||
while (rowResult.next()) { | ||
for (int col = 1; col <= columnCount; col++) { | ||
Object value = rowResult.getObject(col); | ||
if (value != null) { | ||
contents.add(value.toString()); | ||
} | ||
} | ||
} | ||
rowResult.close(); | ||
|
||
} catch (Exception e) { | ||
e.printStackTrace(); | ||
} | ||
|
||
return this.contents; | ||
} | ||
|
||
} | ||
``` | ||
|
||
The ActiveDatabase class is used as an object which contains all necessary information pertaining to setting up the database connection. | ||
```java | ||
public class ActiveDatabase { | ||
|
||
final String dbDomain; | ||
final String dbName; | ||
final String username; | ||
final String password; | ||
final String tableName; | ||
|
||
/** | ||
* Constructor needed to instantiate the database object which is used with the MySQLWorkbench | ||
* Database. | ||
* | ||
* @param dbName Name of the database as String. | ||
* @param username Username for the database as String. | ||
* @param password Password for the database as String. | ||
* @param dbDomain The domain for the database as String. Tested on localhost:3306 | ||
* @param tableName Name of the table which you wish to create the active row. | ||
*/ | ||
public ActiveDatabase(String dbName, String username, String password, String dbDomain, | ||
String tableName) { | ||
this.dbDomain = dbDomain; | ||
this.dbName = dbName; | ||
this.username = username; | ||
this.password = password; | ||
this.tableName = tableName; | ||
} | ||
|
||
public String getDbDomain() { | ||
return dbDomain; | ||
} | ||
|
||
public String getDbName() { | ||
return dbName; | ||
} | ||
|
||
public String getUsername() { | ||
return username; | ||
} | ||
|
||
public String getPassword() { | ||
return password; | ||
} | ||
|
||
public String getTableName() { | ||
return tableName; | ||
} | ||
|
||
} | ||
|
||
``` | ||
|
||
## Applicability | ||
Useful for when you require objects which are made up of database rows and may need to manipulate the database during your program. | ||
|
||
![alt text](./etc/active-record.png) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
@startuml | ||
package com.iluwatar.activeobject { | ||
class ActiveDatabase { | ||
~ dbDomain : String | ||
~ dbName : String | ||
~ password : String | ||
~ tableName : String | ||
~ username : String | ||
+ ActiveDatabase(dbName : String, username : String, password : String, dbDomain : String, tableName : String) | ||
+ getDbDomain() : String | ||
+ getDbName() : String | ||
+ getPassword() : String | ||
+ getTableName() : String | ||
+ getUsername() : String | ||
} | ||
class ActiveRow { | ||
~ columnCount : int | ||
~ columns : ArrayList<String> | ||
~ con : Connection | ||
~ contents : ArrayList<String> | ||
~ dataBase : ActiveDatabase | ||
~ delete : String | ||
~ id : String | ||
~ read : String | ||
~ write : String | ||
+ ActiveRow(dataBase : ActiveDatabase, id : String) | ||
+ delete() | ||
+ initialise() | ||
+ read() : ArrayList<String> | ||
+ write() | ||
} | ||
class App { | ||
+ App() | ||
+ main(args : String[]) {static} | ||
} | ||
interface Rowverride { | ||
} | ||
} | ||
ActiveRow --> "-dataBase" ActiveDatabase | ||
@enduml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<!-- | ||
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. | ||
--> | ||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
<modelVersion>4.0.0</modelVersion> | ||
<parent> | ||
<artifactId>java-design-patterns</artifactId> | ||
<groupId>com.iluwatar</groupId> | ||
<version>1.26.0-SNAPSHOT</version> | ||
</parent> | ||
<artifactId>active-record</artifactId> | ||
<dependencies> | ||
<dependency> | ||
<groupId>com.mysql</groupId> | ||
<artifactId>mysql-connector-j</artifactId> | ||
<version>8.0.31</version> | ||
</dependency> | ||
<dependency> | ||
<groupId>org.junit.jupiter</groupId> | ||
<artifactId>junit-jupiter-engine</artifactId> | ||
<scope>test</scope> | ||
</dependency> | ||
</dependencies> | ||
<properties> | ||
<maven.compiler.source>15</maven.compiler.source> | ||
<maven.compiler.target>15</maven.compiler.target> | ||
</properties> | ||
|
||
<build> | ||
<plugins> | ||
<!-- Maven assembly plugin is invoked with default setting which we have | ||
in parent pom and specifying the class having main method --> | ||
<plugin> | ||
<groupId>org.apache.maven.plugins</groupId> | ||
<artifactId>maven-assembly-plugin</artifactId> | ||
<executions> | ||
<execution> | ||
<configuration> | ||
<archive> | ||
<manifest> | ||
<mainClass>active-record</mainClass> | ||
</manifest> | ||
</archive> | ||
</configuration> | ||
</execution> | ||
</executions> | ||
</plugin> | ||
</plugins> | ||
</build> | ||
|
||
</project> |
Oops, something went wrong.