JDBC removed...

This commit is contained in:
Amit Dixit 2016-04-04 12:24:15 +05:30
parent 28a5a43a47
commit deb15e2733
5 changed files with 433 additions and 541 deletions

View File

@ -1,105 +1,104 @@
/** /**
* The MIT License Copyright (c) 2014 Ilkka Seppälä * The MIT License Copyright (c) 2014 Ilkka Seppälä
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * 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, * associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, * 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 * 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: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all copies or * The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software. * substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * 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 * 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, * 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, * 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. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.apache.log4j.Logger;
/**
/** *
* * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the
* The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * database. Its responsibility is to transfer data between the two and also to isolate them from
* database. Its responsibility is to transfer data between the two and also to isolate them from * each other. With Data Mapper the in-memory objects needn't know even that there's a database
* each other. With Data Mapper the in-memory objects needn't know even that there's a database * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The
* present; they need no SQL interface code, and certainly no knowledge of the database schema. (The * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper ,
* database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , * Data Mapper itself is even unknown to the domain layer.
* Data Mapper itself is even unknown to the domain layer. * <p>
* <p> * The below example demonstrates basic CRUD operations: Create, Read, Update, and Delete.
* The below example demonstrates basic CRUD operations: select, add, update, and delete. *
* */
*/ public final class App {
public final class App {
private static Logger log = Logger.getLogger(App.class);
private static Logger log = Logger.getLogger(App.class);
private static final String DB_TYPE_ORACLE = "Oracle";
private static final String DB_TYPE_ORACLE = "Oracle"; private static final String DB_TYPE_MYSQL = "MySQL";
private static final String DB_TYPE_MYSQL = "MySQL";
/**
/** * Program entry point.
* Program entry point. *
* * @param args command line args.
* @param args command line args. */
*/ public static final void main(final String... args) {
public static final void main(final String... args) {
if (log.isInfoEnabled() & args.length > 0) {
if (log.isInfoEnabled() & args.length > 0) { log.debug("App.main(), db type: " + args[0]);
log.debug("App.main(), db type: " + args[0]); }
}
StudentDataMapper mapper = null;
StudentDataMapper mapper = null;
/* Check the desired db type from runtime arguments */
/* Check the desired db type from runtime arguments */ if (args.length == 0) {
if (args.length == 0) {
/* Create default data mapper for mysql */
/* Create default data mapper for mysql */ mapper = new StudentMySQLDataMapper();
mapper = new StudentMySQLDataMapper();
} else if (args.length > 0 && DB_TYPE_ORACLE.equalsIgnoreCase(args[0])) {
} else if (args.length > 0 && DB_TYPE_ORACLE.equalsIgnoreCase(args[0])) {
/* Create new data mapper for mysql */
/* Create new data mapper for mysql */ mapper = new StudentMySQLDataMapper();
mapper = new StudentMySQLDataMapper();
} else if (args.length > 0 && DB_TYPE_MYSQL.equalsIgnoreCase(args[0])) {
} else if (args.length > 0 && DB_TYPE_MYSQL.equalsIgnoreCase(args[0])) {
/* Create new data mapper for oracle */
/* Create new data mapper for oracle */ mapper = new StudentMySQLDataMapper();
mapper = new StudentMySQLDataMapper(); } else {
} else {
/* Don't couple any Data Mapper to java.sql.SQLException */
/* Don't couple any Data Mapper to java.sql.SQLException */ throw new DataMapperException("Following data mapping type(" + args[0] + ") is not supported");
throw new DataMapperException("Following data source(" + args[0] + ") is not supported"); }
}
/* Create new student */
/* Create new student */ Student student = new Student(1, "Adam", 'A');
Student student = new Student(UUID.randomUUID(), 1, "Adam", 'A');
/* Add student in respectibe db */
/* Add student in respectibe db */ mapper.insert(student);
mapper.insert(student);
/* Find this student */
/* Find this student */ final Optional<Student> studentToBeFound = mapper.find(student.getStudentId());
final Optional<Student> studentToBeFound = mapper.find(student.getGuId());
if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) { log.debug("App.main(), db find returned : " + studentToBeFound);
log.debug("App.main(), db find returned : " + studentToBeFound); }
}
/* Update existing student object */
/* Update existing student object */ student = new Student(student.getStudentId(), "AdamUpdated", 'A');
student = new Student(student.getGuId(), 1, "AdamUpdated", 'A');
/* Update student in respectibe db */
/* Update student in respectibe db */ mapper.update(student);
mapper.update(student);
/* Delete student in db */
/* Delete student in db */ mapper.delete(student);
mapper.delete(student); }
}
private App() {}
private App() {} }
}

View File

@ -1,83 +1,103 @@
/** /**
* The MIT License Copyright (c) 2016 Amit Dixit * The MIT License Copyright (c) 2016 Amit Dixit
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * 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, * associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, * 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 * 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: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all copies or * The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software. * substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * 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 * 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, * 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, * 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. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.io.Serializable;
import java.util.UUID; import java.io.Serializable;
public final class Student implements Serializable { public final class Student implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private UUID guid; private int studentId;
private int studentID; private String name;
private String name; private char grade;
private char grade;
public Student() {
public Student() {
this.guid = UUID.randomUUID(); }
}
public Student(final int studentId, final String name, final char grade) {
public Student(final UUID guid, final int studentID, final String name, final char grade) { super();
super();
this.studentId = studentId;
this.guid = guid; this.name = name;
this.studentID = studentID; this.grade = grade;
this.name = name; }
this.grade = grade;
} public final int getStudentId() {
return studentId;
}
public Student(final UUID guid) {
this.guid = guid; public final void setStudentId(final int studentId) {
} this.studentId = studentId;
}
public final int getStudentId() {
return studentID; public final String getName() {
} return name;
}
public final void setStudentId(final int studentID) {
this.studentID = studentID; public final void setName(final String name) {
} this.name = name;
}
public final String getName() {
return name; public final char getGrade() {
} return grade;
}
public final void setName(final String name) {
this.name = name; public final void setGrade(final char grade) {
} this.grade = grade;
}
public final char getGrade() {
return grade; @Override
} public boolean equals(final Object inputObject) {
public final void setGrade(final char grade) { boolean isEqual = false;
this.grade = grade;
} /* Check if both objects are same */
if (this == inputObject) {
public final UUID getGuId() {
return guid; isEqual = true;
} }
/* Check if objects belong to same class */
@Override else if (inputObject != null && getClass() == inputObject.getClass()) {
public final String toString() {
return "Student [guid=" + guid + ", studentID=" + studentID + ", name=" + name + ", grade=" + grade + "]"; final Student student = (Student) inputObject;
}
} /* If student id matched */
if (this.getStudentId() == student.getStudentId()) {
isEqual = true;
}
}
return isEqual;
}
@Override
public int hashCode() {
/* Student id is assumed to be unique */
return this.getStudentId();
}
@Override
public final String toString() {
return "Student [studentId=" + studentId + ", name=" + name + ", grade=" + grade + "]";
}
}

View File

@ -1,33 +1,32 @@
/** /**
* The MIT License Copyright (c) 2016 Amit Dixit * The MIT License Copyright (c) 2016 Amit Dixit
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * 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, * associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, * 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 * 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: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all copies or * The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software. * substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * 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 * 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, * 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, * 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. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
public interface StudentDataMapper {
public interface StudentDataMapper {
public Optional<Student> find(final int studentId);
public Optional<Student> find(final UUID uniqueID) throws DataMapperException;
public void insert(final Student student) throws DataMapperException;
public void insert(final Student student) throws DataMapperException;
public void update(final Student student) throws DataMapperException;
public void update(final Student student) throws DataMapperException;
public void delete(final Student student) throws DataMapperException;
public void delete(final Student student) throws DataMapperException; }
}

View File

@ -1,160 +1,97 @@
/** /**
* The MIT License Copyright (c) 2016 Amit Dixit * The MIT License Copyright (c) 2016 Amit Dixit
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * 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, * associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, * 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 * 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: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all copies or * The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software. * substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * 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 * 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, * 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, * 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. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.sql.Connection; import java.util.List;
import java.sql.DriverManager; import java.util.Optional;
import java.sql.PreparedStatement;
import java.sql.ResultSet; public final class StudentMySQLDataMapper implements StudentDataMapper {
import java.sql.SQLException;
import java.util.Optional; /* Note: Normally this would be in the form of an actual database */
import java.util.UUID; private List<Student> students;
public final class StudentMySQLDataMapper implements StudentDataMapper { @Override
public final Optional<Student> find(final int studentId) {
@Override
public final Optional<Student> find(final UUID uniqueID) throws DataMapperException { /* Compare with existing students */
for (final Student student : this.students) {
try {
/* OracleDriver class cant be initilized directly */ /* Check if student is found */
Class.forName("oracle.jdbc.driver.OracleDriver"); if (student.getStudentId() == studentId) {
/* Create new connection */ return Optional.of(student);
final Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/MySQL", "username", "password"); }
}
/* Create new Oracle compliant sql statement */
final String statement = "SELECT `guid`, `grade`, `studentID`, `name` FROM `students` where `guid`=?"; /* Return empty value */
final PreparedStatement dbStatement = connection.prepareStatement(statement); return Optional.empty();
}
/* Set unique id in sql statement */
dbStatement.setString(1, uniqueID.toString()); @Override
public final void update(final Student studentToBeUpdated) throws DataMapperException {
/* Execute the sql query */
final ResultSet rs = dbStatement.executeQuery();
/* Check with existing students */
while (rs.next()) { if (this.students.contains(studentToBeUpdated)) {
/* Create new student */ /* Get the index of student in list */
final Student student = new Student(UUID.fromString(rs.getString("guid"))); final int index = this.students.indexOf(studentToBeUpdated);
/* Set all values from database in java object */ /* Update the student in list */
student.setName(rs.getString("name")); this.students.set(index, studentToBeUpdated);
student.setGrade(rs.getString("grade").charAt(0));
student.setStudentId(rs.getInt("studentID")); } else {
return Optional.of(student); /* Throw user error */
} throw new DataMapperException("Student [" + studentToBeUpdated.getName() + "] is not found");
} catch (final SQLException | ClassNotFoundException e) { }
}
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from MySQL data source.", e); @Override
} public final void insert(final Student studentToBeInserted) throws DataMapperException {
/* Return empty value */ /* Check with existing students */
return Optional.empty(); if (!this.students.contains(studentToBeInserted)) {
}
/* Add student in list */
@Override this.students.add(studentToBeInserted);
public final void update(final Student student) throws DataMapperException {
try { } else {
/* OracleDriver class cant be initilized directly */ /* Throw user error */
Class.forName("oracle.jdbc.driver.OracleDriver"); throw new DataMapperException("Student already [" + studentToBeInserted.getName() + "] exists");
}
/* Create new connection */ }
final Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/MySQL", "username", "password");
@Override
/* Create new Oracle compliant sql statement */ public final void delete(final Student studentToBeDeleted) throws DataMapperException {
final String statement = "UPDATE `students` SET `grade`=?, `studentID`=?, `name`=? where `guid`=?";
/* Check with existing students */
final PreparedStatement dbStatement = connection.prepareStatement(statement); if (this.students.contains(studentToBeDeleted)) {
/* Set java object values in sql statement */ /* Delete the student from list */
dbStatement.setString(1, Character.toString(student.getGrade())); this.students.remove(studentToBeDeleted);
dbStatement.setInt(2, student.getStudentId());
dbStatement.setString(3, student.getName()); } else {
dbStatement.setString(4, student.getGuId().toString());
/* Throw user error */
/* Execute the sql query */ throw new DataMapperException("Student [" + studentToBeDeleted.getName() + "] is not found");
dbStatement.executeUpdate(); }
}
} catch (final SQLException | ClassNotFoundException e) { }
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from MySQL data source.", e);
}
}
@Override
public final void insert(final Student student) throws DataMapperException {
try {
/* OracleDriver class cant be initilized directly */
Class.forName("oracle.jdbc.driver.OracleDriver");
/* Create new connection */
final Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/MySQL", "username", "password");
/* Create new Oracle compliant sql statement */
final String statement = "INSERT INTO `students` (`grade`, `studentID`, `name`, `guid`) VALUES (?, ?, ?, ?)";
final PreparedStatement dbStatement = connection.prepareStatement(statement);
/* Set java object values in sql statement */
dbStatement.setString(1, Character.toString(student.getGrade()));
dbStatement.setInt(2, student.getStudentId());
dbStatement.setString(3, student.getName());
dbStatement.setString(4, student.getGuId().toString());
/* Execute the sql query */
dbStatement.executeUpdate();
} catch (final SQLException | ClassNotFoundException e) {
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from MySQL data source.", e);
}
}
@Override
public final void delete(final Student student) throws DataMapperException {
try {
/* OracleDriver class cant be initilized directly */
Class.forName("oracle.jdbc.driver.OracleDriver");
/* Create new connection */
final Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/MySQL", "username", "password");
/* Create new Oracle compliant sql statement */
final String statement = "DELETE FROM `students` where `guid`=?";
final PreparedStatement dbStatement = connection.prepareStatement(statement);
/* Set java object values in sql statement */
dbStatement.setString(1, student.getGuId().toString());
/* Execute the sql query */
dbStatement.executeUpdate();
} catch (final SQLException | ClassNotFoundException e) {
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from MySQL data source.", e);
}
}
}

View File

@ -1,160 +1,97 @@
/** /**
* The MIT License Copyright (c) 2016 Amit Dixit * The MIT License Copyright (c) 2016 Amit Dixit
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * 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, * associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, * 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 * 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: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all copies or * The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software. * substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * 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 * 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, * 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, * 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. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.sql.Connection; import java.util.List;
import java.sql.DriverManager; import java.util.Optional;
import java.sql.PreparedStatement;
import java.sql.ResultSet; public final class StudentOracleDataMapper implements StudentDataMapper {
import java.sql.SQLException;
import java.util.Optional; /* Note: Normally this would be in the form of an actual database */
import java.util.UUID; private List<Student> students;
public final class StudentOracleDataMapper implements StudentDataMapper { @Override
public final Optional<Student> find(final int studentId) {
@Override
public final Optional<Student> find(final UUID uniqueID) throws DataMapperException { /* Compare with existing students */
for (final Student student : this.students) {
try {
/* OracleDriver class cant be initilized directly */ /* Check if student is found */
Class.forName("oracle.jdbc.driver.OracleDriver"); if (student.getStudentId() == studentId) {
/* Create new connection */ return Optional.of(student);
final Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Oracle", "username", "password"); }
}
/* Create new Oracle compliant sql statement */
final String statement = "SELECT `guid`, `grade`, `studentID`, `name` FROM `students` where `guid`=?"; /* Return empty value */
final PreparedStatement dbStatement = connection.prepareStatement(statement); return Optional.empty();
}
/* Set unique id in sql statement */
dbStatement.setString(1, uniqueID.toString()); @Override
public final void update(final Student studentToBeUpdated) throws DataMapperException {
/* Execute the sql query */
final ResultSet rs = dbStatement.executeQuery();
/* Check with existing students */
while (rs.next()) { if (this.students.contains(studentToBeUpdated)) {
/* Create new student */ /* Get the index of student in list */
final Student student = new Student(UUID.fromString(rs.getString("guid"))); final int index = this.students.indexOf(studentToBeUpdated);
/* Set all values from database in java object */ /* Update the student in list */
student.setName(rs.getString("name")); this.students.set(index, studentToBeUpdated);
student.setGrade(rs.getString("grade").charAt(0));
student.setStudentId(rs.getInt("studentID")); } else {
return Optional.of(student); /* Throw user error */
} throw new DataMapperException("Student [" + studentToBeUpdated.getName() + "] is not found");
} catch (final SQLException | ClassNotFoundException e) { }
}
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from Oracle data source.", e); @Override
} public final void insert(final Student studentToBeInserted) throws DataMapperException {
/* Return empty value */ /* Check with existing students */
return Optional.empty(); if (!this.students.contains(studentToBeInserted)) {
}
/* Add student in list */
@Override this.students.add(studentToBeInserted);
public final void update(final Student student) throws DataMapperException {
try { } else {
/* OracleDriver class cant be initilized directly */ /* Throw user error */
Class.forName("oracle.jdbc.driver.OracleDriver"); throw new DataMapperException("Student already [" + studentToBeInserted.getName() + "] exists");
}
/* Create new connection */ }
final Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Oracle", "username", "password");
@Override
/* Create new Oracle compliant sql statement */ public final void delete(final Student studentToBeDeleted) throws DataMapperException {
final String statement = "UPDATE `students` SET `grade`=?, `studentID`=?, `name`=? where `guid`=?";
/* Check with existing students */
final PreparedStatement dbStatement = connection.prepareStatement(statement); if (this.students.contains(studentToBeDeleted)) {
/* Set java object values in sql statement */ /* Delete the student from list */
dbStatement.setString(1, Character.toString(student.getGrade())); this.students.remove(studentToBeDeleted);
dbStatement.setInt(2, student.getStudentId());
dbStatement.setString(3, student.getName()); } else {
dbStatement.setString(4, student.getGuId().toString());
/* Throw user error */
/* Execute the sql query */ throw new DataMapperException("Student [" + studentToBeDeleted.getName() + "] is not found");
dbStatement.executeUpdate(); }
}
} catch (final SQLException | ClassNotFoundException e) { }
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from Oracle data source.", e);
}
}
@Override
public final void insert(final Student student) throws DataMapperException {
try {
/* OracleDriver class cant be initilized directly */
Class.forName("oracle.jdbc.driver.OracleDriver");
/* Create new connection */
final Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Oracle", "username", "password");
/* Create new Oracle compliant sql statement */
final String statement = "INSERT INTO `students` (`grade`, `studentID`, `name`, `guid`) VALUES (?, ?, ?, ?)";
final PreparedStatement dbStatement = connection.prepareStatement(statement);
/* Set java object values in sql statement */
dbStatement.setString(1, Character.toString(student.getGrade()));
dbStatement.setInt(2, student.getStudentId());
dbStatement.setString(3, student.getName());
dbStatement.setString(4, student.getGuId().toString());
/* Execute the sql query */
dbStatement.executeUpdate();
} catch (final SQLException | ClassNotFoundException e) {
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from Oracle data source.", e);
}
}
@Override
public final void delete(final Student student) throws DataMapperException {
try {
/* OracleDriver class cant be initilized directly */
Class.forName("oracle.jdbc.driver.OracleDriver");
/* Create new connection */
final Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Oracle", "username", "password");
/* Create new Oracle compliant sql statement */
final String statement = "DELETE FROM `students` where `guid`=?";
final PreparedStatement dbStatement = connection.prepareStatement(statement);
/* Set java object values in sql statement */
dbStatement.setString(1, student.getGuId().toString());
/* Execute the sql query */
dbStatement.executeUpdate();
} catch (final SQLException | ClassNotFoundException e) {
/* Don't couple any Data Mapper to java.sql.SQLException */
throw new DataMapperException("Error occured reading Students from Oracle data source.", e);
}
}
}