public class GenericViewDAO<B> extends Object
Here is an example of a bean representing a student:
public class Student { private String studentId; private String firstName; private String lastName; private double gpa; public String getStudentId() { return studentId; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getGpa() { return gpa; } public void setStudentId(String s) { studentId = s; } public void setFirstName(String s) { firstName = s; } public void setLastName(String s) { lastName = s; } public void setGpa(double d) { gpa = d; } }
To use this class, instantiate it in the usual way and then call executeQuery(). Provide a SQL query that produces a table that contains a field for every property of the StudentId JavaBean. To prevent injection attacks, pass user data as separate parameters. Here are some examples:
String sql = "select studentId, firstName, lastName, gpa from student"; StudentId[] a = executeQuery(sql); String sql = "select studentId, firstName, lastName, gpa from student where firstName='Fred'"; StudentId[] a = executeQuery(sql); String sql = "select studentId, firstName, lastName, gpa from student where firstName=?"; StudentId[] a = executeQuery(sql, request.getParameter("firstName")); String sql = "select student.id as studentId, student.first as firstName, " + "student.last as lastName, grades.average as gpa " + "from student, grades"; StudentId[] a = executeQuery(sql); String sql = "select student.id as studentId, student.first as firstName, " + "student.last as lastName, grades.average as gpa " + "from student, grades where student.id=?"; StudentId[] a = executeQuery(sql, request.getParameter("id")); Student s = null; if (a.length != 0) { s = a[0]; }
Constructor and Description |
---|
GenericViewDAO(Class<B> beanClass,
ConnectionPool connectionPool)
Constructor
|
Modifier and Type | Method and Description |
---|---|
B[] |
executeQuery(String sql,
Object... args)
Runs a query using the provided SQL and parameters.
|
String[] |
getPropertyNames() |
public GenericViewDAO(Class<B> beanClass, ConnectionPool connectionPool) throws DAOException
beanClass
- the class description of the bean.connectionPool
- the connection pool to use to manage connections to the
database.DAOException
- if there are any problems, including problems accessing the
database, problems with the bean class, etc.public B[] executeQuery(String sql, Object... args) throws RollbackException
sql
- a SQL query, as would be passed to a PreparedStatement.args
- arguments for the SQL query (if any).null
.)RollbackException
- if there are errors in the types of the arguments, or
if there is an error accessing the database, including
SQLException or deadlock.public String[] getPropertyNames()
Copyright © 2012-2016 Jeffrey L. Eppinger. All rights reserved. Permission granted for educational use only.