feature: Embedded value pattern (#2384)

* Emdedded value design pattern

* Adding suggested changes

* Adding module in parent POM

* Fixed checkstyle errors
This commit is contained in:
Shivanagouda Agasimani
2022-12-04 22:01:29 +05:30
committed by GitHub
parent 7d2832f412
commit b2eb312b5e
11 changed files with 826 additions and 0 deletions
@@ -0,0 +1,114 @@
/*
* 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.embedded.value;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/*
* Many small objects make sense in an OO system that dont make sense as
* tables in a database. Examples include currency-aware money objects (amount, currency) and date
* ranges. Although the default thinking is to save an object as a table, no sane
* person would want a table of money values.
*
* An Embedded Value maps the values of an object to fields in the record of
* the objects owner. In this implementation we have an Order object with links to an
* ShippingAddress object. In the resulting table the fields in the ShippingAddress
* object map to fields in the Order table rather than make new records
* themselves.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args.
* @throws Exception if any error occurs.
*
*/
public static void main(String[] args) throws Exception {
final var dataSource = new DataSource();
// Orders to insert into database
final var order1 = new Order("JBL headphone", "Ram",
new ShippingAddress("Bangalore", "Karnataka", "560040"));
final var order2 = new Order("MacBook Pro", "Manjunath",
new ShippingAddress("Bangalore", "Karnataka", "581204"));
final var order3 = new Order("Carrie Soto is Back", "Shiva",
new ShippingAddress("Bangalore", "Karnataka", "560004"));
/**
* Create table for orders - Orders(id, name, orderedBy, city, state, pincode).
* We can see that table is different from the Order object we have.
* We're mapping ShippingAddress into city, state, pincode colummns of the database and not creating a separate table.
*/
if (dataSource.createSchema()) {
LOGGER.info("TABLE CREATED");
LOGGER.info("Table \"Orders\" schema:\n" + dataSource.getSchema());
} else {
//If not able to create table, there's nothing we can do further.
LOGGER.error("Error creating table");
System.exit(0);
}
// Initially, database is empty
LOGGER.info("Orders Query: {}", dataSource.queryOrders().collect(Collectors.toList()));
//Insert orders where shippingAddress is mapped to different columns of the same table
dataSource.insertOrder(order1);
dataSource.insertOrder(order2);
dataSource.insertOrder(order3);
/**
* Query orders
* We'll create ShippingAddress object from city, state, pincode values from the table
* and add it to Order object
*/
LOGGER.info("Orders Query: {}", dataSource.queryOrders().collect(Collectors.toList()) + "\n");
//Query order by given id
LOGGER.info("Query Order with id=2: {}", dataSource.queryOrder(2));
/**
* Remove order by given id.
* Since we'd mapped address in the same table, deleting order will also take
* out the shipping address details
*/
LOGGER.info("Remove Order with id=1");
dataSource.removeOrder(1);
LOGGER.info("\nOrders Query: {}", dataSource.queryOrders().collect(Collectors.toList()) + "\n");
//After successfull demonstration of the pattern, drop the table
if (dataSource.deleteSchema()) {
LOGGER.info("TABLE DROPPED");
} else {
//If there's a potential error while dropping table
LOGGER.error("Error deleting table");
}
}
}
@@ -0,0 +1,217 @@
/*
* 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.embedded.value;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
/*
* Communicates with H2 database with the help of JDBC API
*
* Inherits the SQL queries and methods from @link AbstractDataSource class
*/
@Slf4j
public class DataSource implements DataSourceInterface {
private Connection conn;
/**
* Statements are objects which are used to execute queries which will not be
* repeated.
*/
private Statement getschema;
private Statement deleteschema;
private Statement queryOrders;
/*
* PreparedStatements are used to execute queries which will be repeated.
*/
private PreparedStatement insertIntoOrders;
private PreparedStatement removeorder;
private PreparedStatement queyOrderByID;
/**
* {@summary}
* Establish connection to database.
*/
public DataSource() {
try {
conn = DriverManager.getConnection(JDBC_URL);
LOGGER.info("Connected to H2 in-memory database: " + conn.getCatalog());
} catch (SQLException e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
}
}
@Override
public boolean createSchema() {
try (Statement createschema = conn.createStatement()) {
createschema.execute(CREATE_SCHEMA);
insertIntoOrders = conn.prepareStatement(INSERT_ORDER, PreparedStatement.RETURN_GENERATED_KEYS);
getschema = conn.createStatement();
queryOrders = conn.createStatement();
removeorder = conn.prepareStatement(REMOVE_ORDER);
queyOrderByID = conn.prepareStatement(QUERY_ORDER);
deleteschema = conn.createStatement();
} catch (SQLException e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
return false;
}
return true;
}
@Override
public String getSchema() {
try {
var resultSet = getschema.executeQuery(GET_SCHEMA);
var sb = new StringBuilder();
while (resultSet.next()) {
sb.append("Col name: " + resultSet.getString(1) + ", Col type: " + resultSet.getString(2) + "\n");
}
getschema.close();
return sb.toString();
} catch (Exception e) {
LOGGER.error("Error in retrieving schema: {}", e.getLocalizedMessage(), e.getCause());
}
return "Schema unavailable";
}
@Override
public boolean insertOrder(Order order) {
try {
conn.setAutoCommit(false);
insertIntoOrders.setString(1, order.getItem());
insertIntoOrders.setString(2, order.getOrderedBy());
var address = order.getShippingAddress();
insertIntoOrders.setString(3, address.getCity());
insertIntoOrders.setString(4, address.getState());
insertIntoOrders.setString(5, address.getPincode());
var affectedRows = insertIntoOrders.executeUpdate();
if (affectedRows == 1) {
var rs = insertIntoOrders.getGeneratedKeys();
rs.last();
var insertedAddress = new ShippingAddress(address.getCity(), address.getState(), address.getPincode());
var insertedOrder = new Order(rs.getInt(1), order.getItem(), order.getOrderedBy(),
insertedAddress);
conn.commit();
LOGGER.info("Inserted: {}", insertedOrder);
} else {
conn.rollback();
}
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage());
} finally {
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
LOGGER.error(e.getLocalizedMessage());
}
}
return true;
}
@Override
public Stream<Order> queryOrders() {
var ordersList = new ArrayList<Order>();
try (var rSet = queryOrders.executeQuery(QUERY_ORDERS)) {
while (rSet.next()) {
var order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3),
new ShippingAddress(rSet.getString(4), rSet.getString(5),
rSet.getString(6)));
ordersList.add(order);
}
rSet.close();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e.getCause());
}
return ordersList.stream();
}
/**
* {@summary}
* Query order by given id.
* @param id as the parameter
* @return Order objct
* @throws SQLException in case of unexpected events
*/
@Override
public Order queryOrder(int id) throws SQLException {
Order order = null;
queyOrderByID.setInt(1, id);
try (var rSet = queyOrderByID.executeQuery()) {
queyOrderByID.setInt(1, id);
if (rSet.next()) {
var address = new ShippingAddress(rSet.getString(4),
rSet.getString(5), rSet.getString(6));
order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3), address);
}
rSet.close();
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
}
return order;
}
@Override
public void removeOrder(int id) throws Exception {
try {
conn.setAutoCommit(false);
removeorder.setInt(1, id);
if (removeorder.executeUpdate() == 1) {
LOGGER.info("Order with id " + id + " successfully removed");
} else {
LOGGER.info("Order with id " + id + " unavailable.");
}
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
conn.rollback();
} finally {
conn.setAutoCommit(true);
}
}
@Override
public boolean deleteSchema() throws Exception {
try {
deleteschema.execute(DELETE_SCHEMA);
queryOrders.close();
queyOrderByID.close();
deleteschema.close();
insertIntoOrders.close();
conn.close();
return true;
} catch (Exception e) {
LOGGER.error(e.getLocalizedMessage(), e.getCause());
}
return false;
}
}
@@ -0,0 +1,69 @@
/*
* 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.embedded.value;
import java.sql.SQLException;
import java.util.stream.Stream;
/*
* Abstract class which contains the required SQL queries and basic methods declaration.
*
* The main thing to consider is that the ShippingAddress object doesn't have it's own class
* but it's values are stored into the Orders table as city, state, pincode
*
*/
interface DataSourceInterface {
final String JDBC_URL = "jdbc:h2:mem:Embedded-Value";
final String CREATE_SCHEMA = "CREATE TABLE Orders (Id INT AUTO_INCREMENT, item VARCHAR(50) NOT NULL, orderedBy VARCHAR(50)"
+ ", city VARCHAR(50), state VARCHAR(50), pincode CHAR(6) NOT NULL, PRIMARY KEY(Id))";
final String GET_SCHEMA = "SHOW COLUMNS FROM Orders";
final String INSERT_ORDER = "INSERT INTO Orders (item, orderedBy, city, state, pincode) VALUES(?, ?, ?, ?, ?)";
final String QUERY_ORDERS = "SELECT * FROM Orders";
final String QUERY_ORDER = QUERY_ORDERS + " WHERE Id = ?";
final String REMOVE_ORDER = "DELETE FROM Orders WHERE Id = ?";
final String DELETE_SCHEMA = "DROP TABLE Orders";
boolean createSchema() throws SQLException;
String getSchema() throws SQLException;
boolean insertOrder(Order order) throws SQLException;
Stream<Order> queryOrders() throws SQLException;
Order queryOrder(int id) throws SQLException;
void removeOrder(int id) throws Exception;
boolean deleteSchema() throws Exception;
}
@@ -0,0 +1,61 @@
/*
* 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.embedded.value;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* A POJO which represents the Order object.
*/
@ToString
@Setter
@Getter
public class Order {
private int id;
private String item;
private String orderedBy;
private ShippingAddress shippingAddress;
/**
* Constructor for Item object.
* @param item item name
* @param orderedBy item orderer
* @param shippingAddress shipping address details
*/
public Order(String item, String orderedBy, ShippingAddress shippingAddress) {
this.item = item;
this.orderedBy = orderedBy;
this.shippingAddress = shippingAddress;
}
public Order(int id, String item, String orderedBy, ShippingAddress shippingAddress) {
this(item, orderedBy, shippingAddress);
this.id = id;
}
}
@@ -0,0 +1,54 @@
/*
* 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.embedded.value;
import lombok.Getter;
import lombok.ToString;
/**
* Another POJO which wraps the Shipping details of order into Object.
*/
@ToString
@Getter
public class ShippingAddress {
private String city;
private String state;
private String pincode;
/**
* Constructor for Shipping Address object.
* @param city City name
* @param state State name
* @param pincode Pin code of the city
*
*/
public ShippingAddress(String city, String state, String pincode) {
this.city = city;
this.state = state;
this.pincode = pincode;
}
}