Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Active record pattern #1

Merged
merged 20 commits into from
Oct 30, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions active-record/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
title: Active Record
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved
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.
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved

## Explanation
The ActiveRecord object is intitialised by an ActiveDatabase object which creates a connection to an exisitng database.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This explanation is not sufficient. Please see other examples in the repo for what is to be expected.


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 but do not have sufficient SQL knowledge to do so.

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.
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved
40 changes: 40 additions & 0 deletions active-record/etc/active-record.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
@startuml
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved
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
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved
49 changes: 49 additions & 0 deletions active-record/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.iluwatar.activeobject;

import java.sql.SQLException;

/**
* This class initialises frequently needed variables for the MySQLWorkbench Database.
*/
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;
}

}
159 changes: 159 additions & 0 deletions active-record/src/main/java/com/iluwatar/activeobject/ActiveRow.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package com.iluwatar.activeobject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
* ActiveRow attempts to implement the fundamental ruby on rails 'Active Record' design pattern in
* 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("'");
query.append(con);
query.append("' ");
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved
query.append(",");
} else {
query.append("'");
query.append(con);
query.append("' ");
query.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;
}

}
30 changes: 30 additions & 0 deletions active-record/src/main/java/com/iluwatar/activeobject/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.iluwatar.activeobject;

import java.util.ArrayList;
import java.util.Arrays;

/**
* Useful examples of common useage of the program.
*/
public class App {

/**
* Use this method to become familiar with the program.
*
* @param args arguments passed into the main method.
*/
public static void main(String[] args) {
try {
ActiveDatabase activeDatabase = new ActiveDatabase("world", "root", "apple-trunks", "localhost:3306", "city");
ActiveRow ar = new ActiveRow(activeDatabase, "101");
ar.contents = new ArrayList<String>(
Arrays.asList("101", "Godoy Cruz", "ARG", "Mendoza", "206998"));
ar.write();
System.out.println(ar.read());

} catch (Exception e) {
e.printStackTrace();
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.iluwatar.activeobject;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Rowverride {

}
TwentyVentti marked this conversation as resolved.
Show resolved Hide resolved
Loading