Getting values from Get and Set methods using separate classes [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to Java:
I have the following program that connects to different databases using an Enum to call the different database connection.
I need to put the credentials, username and password in a class by itself but I am not sure because they are both initialized using get and set and the only way I can get this to work is called them both in the same method.
First I have this class which initializes the connection strings and data elements.
class DatabaseUtility {
private String USERNAME;
private String PASSWORD;
private String HSQLDB;
private String MYSQL;
public DatabaseUtility() {
USERNAME = null;
PASSWORD = null;
HSQLDB = null;
MYSQL = null;
}
public String getUsername() {
return USERNAME;
}
public void setUsername(String username) {
USERNAME = username;
}
public String getPassword() {
return PASSWORD;
}
public void setPassword(String password) {
PASSWORD = password;
}
public String getHsdbConn() {
return HSQLDB;
}
public void setHsdb(String hsdbConnection) {
HSQLDB = hsdbConnection;
}
public String getMySqlConn() {
return MYSQL;
}
public void setMySqlConn(String mySqlConnection) {
MYSQL = mySqlConnection;
}
}
Next I have an enum use to call both db types:
public enum DBType {
HSQLDB, MYSQL
}
Next I have a method which uses a switch statement to assign the different db connection based on the user preference in the main method.
*This is the focus of my post, I have to call both the get and set methods in here, I would rather not set the credentials in the same method but not sure how to separate the two.
import java.sql.*;
class DatabaseConnectivity {
DatabaseUtility dbUtil = new DatabaseUtility();
public Connection getConnection(DBType dbType) throws SQLException {
dbUtil.setHsdb("jdbc:hsqldb:data/explorecalifornia");
dbUtil.setMySqlConn("jdbc:mysql://jsa/explorecalifornia");
dbUtil.setUsername("dbuser");
dbUtil.setPassword("dbpassword");
switch (dbType) {
case MYSQL:
return DriverManager.getConnection(dbUtil.getMySqlConn(),
dbUtil.getUsername(), dbUtil.getPassword());
case HSQLDB:
return DriverManager.getConnection(dbUtil.getHsdbConn(),
dbUtil.getUsername(), dbUtil.getPassword());
default:
return null;
}
}
}
Finally, here is the main class, notice the DBType enum called in the try catch block.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MultiDatabaseConnectionMain {
public static void main(String[] args) throws SQLException {
DatabaseConnectivity databaseConnectivity = new DatabaseConnectivity();
Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
try {
connection = databaseConnectivity.getConnection(DBType.MYSQL);
System.out.println("Connected");
System.out.println();
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
resultset = statement.executeQuery("SELECT * FROM states");
resultset.last();
System.out.println("Number of rows: " + resultset.getRow());
} catch (SQLException e) {
System.err.println(e);
} finally {
if (resultset != null) {
resultset.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
}

I am not 100% sure, but I think what you are asking is that you have to call dbUtil.set* and dbUtil.get* in the same method.
What I would suggest is that you create enum with db properties so whatever dbType passed to the argument you can just call getters on them. You can define your enum as below.
public enum DBType {
//ser properties you want for db. url, username are just dummy values
HSQLDB("url", "username", "password"), MYSQL("url", "username", "password");
private String url;
private String username;
private String password;
private DBType(String url, String username, String password){
this.url = url;
//set other properties
}
public String getUrl(){
return this.url;
}
//getter for all the other values
}
and in DatabaseConnectivity's getConnection method will be
public Connection getConnection(DBType dbType) throws SQLException {
return DriverManager.getConnection(dbType.getUrl(),
dbType.getUsername(), dbType.getPasword());
}

You can provide credentials in the constructor of class DatabaseConnectivity and then use them to set values in the instance of DatabaseUtility.
class DatabaseConnectivity {
DatabaseUtility dbUtil;
public DatabaseConnectivity (String userName, String password) {
dbUtil = new DatabaseUtility();
dbUtil.setUsername(userName)
dbUtil.setPassword(password);
}
......

Related

Java Return Null When Tried to Get Method

first of all I know this is duplicated question. But I've search and tried from stackoverflow listed on Google to quora but still cant resolve my Get method still return null.
This is my class loginModel.java under package com.hello.model
public class loginModel {
public String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
}
This is my loginView.java under package com.hello.view
import com.hello.model.loginModel;
public class loginView extends javax.swing.JFrame {
loginModel login = new loginModel();
public loginView() {
initComponents();
this.setLocationRelativeTo(null);
loginFunction();
}
private void loginFunction(){
String username = usernameText.getText();
String password = passwdText.getText();
String query = "select * from access where username = '" +username+ "' AND password = '" +password+"'";
databaseConnect db = new databaseConnect();
try (Connection con = DriverManager.getConnection(db.url, db.user, db.password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if(rs.next()) {
if(username.equals(rs.getString("username")) && password.equals(rs.getString("password"))){
JOptionPane.showMessageDialog(null, "login Success");
String name = rs.getString("name");
String privilege = rs.getString("privilege");
login.setUsername(name);
menu = new menuView();
menu.setVisible(true);
this.setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null, "username or password incorrect");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want call my username from menuView.java under package com.hello.view after login success
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
}
As per my question when I call Get method from loginModel, messagebox return null.
I've tried:
Put system.out.println directly in loginModel.java, value return
and call system.out.println in menuView.java at the same time but value return null. How?
Send string between jframe with menu = menuView(username) in loginView.java and retrieve in menuView.java, value return null
Using no model and create set string in loginView and call it in
menuView, value return null
I need values that I want to use in another class/package/jframe. Am I doing wrong?
I am not well versed in Swing but I can see the problem, just not the exact solution.
Your code creates an instance of loginModel in both the menuView and in loginView. Then in loginView is sets the name in the instance it has, in in menuView it gets the name from its own instance.
You need to create a single instance of the model and share it between the two views.
In a pojo way I would pass the loginModel to both "views" in a constructor.
menu = new menuView(login);
And in menuView
public menuView(loginModel login) {
this.login = login;
}
Your menuView instance isn't using the loginModel class that you instantiate in loginView, it's using the new one you created using new menuView() when you initialized the login variable in the menuView class. You just need to add a setter method for the loginModel attribute in the menuView class like this:
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
public void setLogin(loginModel loginModel) {
this.login = loginModel;
}
}
Then call the setter in loginView.loginFunction like this:
... code before
login.setUsername(name);
menu = new menuView();
menu.setLogin(login);
menu.setVisible(true);
this.setVisible(false);
... code after
Notice the only changes to your code are the added setLogin method on the menuView class and the call to menu.setLogin(login) in loginView.loginFunction.
You need to think in stages/steps. Login is a single step, it has one of two outcomes, success or failure.
Your app needs to perform this step and take appropriate action based on the outcome of the result.
You also need to think about "separation of responsibility" - in this case, it's not really the responsibility of the loginView to perform the login operation, it just coordinates the user input.
The responsibility actually falls to the LoginModel
// Just a custom exception to make it easier to determine
// what actually went wrong
public class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}
// LoginModel ... that "does" stuff
public class LoginModel {
private String username;
DatabaseConnect db;
public LoginModel(DatabaseConnect db) {
this.db = db;
}
// I would consider not doing this. You need to ask what reasons would
// the app need this information and expose it only if there is really a
// reason to do so
public String getUsername() {
return username;
}
public boolean isLogedIn() {
return username != null;
}
public void validate(String username, String password) throws SQLException, LoginException {
String query = "select * from access where username = ? AND password = ?";
try ( Connection con = DriverManager.getConnection(db.url, db.user, db.password); PreparedStatement st = con.prepareStatement(query)) {
st.setString(1, username);
st.setString(2, password);
try ( ResultSet rs = st.executeQuery()) {
if (rs.next()) {
this.username = username;
} else {
throw new LoginException("Invalid user credentials");
}
}
}
}
}
This is an overly simplified example, as the actual responsibility for performing the login should fall to the controller, which would then generate the model, but I'm getting ahead of myself.
Because the flow of the app shouldn't be controlled/determined by the login view, the LoginView should itself be a dialog. This way, it can be shown when you need it, it can perform what ever operations it needs and then go away, leaving the rest of the decision making up to who ever called it
public class LoginView extends javax.swing.JDialog {
private LoginModel model;
public LoginView(LoginModel model) {
initComponents();
setModal(true);
this.model = model;
this.setLocationRelativeTo(null);
}
// This will get executed when the user taps some kind of "perform login button"
private void loginFunction() {
String username = usernameText.getText();
String password = passwdText.getText();
try {
model.validate(username, password);
dispose()
} catch (SQLException ex) {
// This should probably be considered a fatal error
model = null;
dispose();
} catch (LoginException ex) {
JOptionPane.showMessageDialog(this, "Login vaild");
}
}
}
This then means you might put it together something like this...
DatabaseConnect db = new DatabaseConnect();
LoginModel model = new LoginModel(db);
LoginView loginView = new LoginView(model);
// Because we're using a modal dialog, the code execution will wait here
// till the window is disposed/closed
loginView.setVisible(true);
if (loginView.model != null) {
// model is now valid and can continue to be used
// in what ever fashion you need
} else {
JOptionPane.showMessageDialog(null, "Fatal Error");
}
This takes you a step closer to a more decoupled solution, where you feed information to the classes when they need it, rather than the classes making decisions about what they should create/use.
It also moves you a step closer to re-usable classes, as they do their specific job and nothing more.
You might find taking the time to read up on "model-view-controller" will help you better understand this approach

MYSQL JDBC java.sql.SQLException: Operation not allowed after ResultSet closed

I have a program that queries a database using different jdbc drivers. This error is specific to the MySQL driver.
Here's the basic rundown.
I have another query runner class that uses a postgresql jdbc driver that works just fine. Note the line conn.close(); this works fine on my postgresql query runner, but for this SQL runner it comes up with the error.
I have removed the line conn.close(); and this code works fine, but over time it accumulates sleeping connections in the database. How can I fix this?
New Relic is a third party application that I am feeding data to, if you dont know what it is, don't worry it's not very relevant to this error.
MAIN CLASS
public class JavaPlugin {
public static void main(String[] args) {
try {
Runner runner = new Runner();
runner.add(new MonitorAgentFactory());
runner.setupAndRun(); // never returns
}
catch (ConfigurationException e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
}
}
MYSQL QUERY RUNNER CLASS
import com.newrelic.metrics.publish.util.Logger;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLQueryRunner {
private static final Logger logger = Logger.getLogger(MySQLQueryRunner.class);
private String connectionStr;
private String username;
private String password;
public MySQLQueryRunner(String host, long port, String database, String username, String password) {
this.connectionStr = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false";
this.username = username;
this.password = password;
}
private void logError(String message) {
logger.error(new Object[]{message});
}
private void logDebugger(String message) {
logger.debug(new Object[]{message});
}
private Connection establishConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logError("MySQL Driver could not be found");
e.printStackTrace();
return null;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionStr, username, password);
logDebugger("Connection established: " + connectionStr + " using " + username);
} catch (SQLException e) {
logError("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}
public ResultSet run(String query) {
Connection conn = establishConnection();
if (conn == null) {
logError("Connection could not be established");
return null;
}
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
conn.close();
return rs;
} catch (SQLException e) {
logError("Failed to collect data from database");
e.printStackTrace();
return null;
}
}
}
AGENT CLASS
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import com.newrelic.metrics.publish.Agent;
public class LocalAgent extends Agent {
private MySQLQueryRunner queryRunner;
private String name;
private Map<String, Object> thresholds;
private int intervalDuration;
private int intervalCount;
public LocalAgent(String name, String host, long port, String database, String username, String password, Map<String, Object> thresholds, int intervalDuration) {
super("com.mbt.local", "1.0.0");
this.name = name;
this.queryRunner = new MySQLQueryRunner(host, port, database, username, password);
// this.eventPusher = new NewRelicEvent();
this.thresholds = thresholds;
this.intervalDuration = intervalDuration;
this.intervalCount = 0;
}
/**
* Description of query
*/
private void eventTestOne() {
String query = "select count(1) as jerky from information_schema.tables;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestOne");
event.add("jerky", rs.getInt("jerky"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* blah
*/
private void eventTestTwo() {
String query = "SELECT maxlen FROM information_schema.CHARACTER_SETS;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestTwo");
event.add("beef", rs.getString("maxlen"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void pollCycle() {
if (this.intervalCount % this.intervalDuration == 0) {
eventTestOne();
eventTestTwo();
this.intervalCount = 0;
}
// Always incrementing intervalCount, keeping track of poll cycles that have passed
this.intervalCount++;
}
#Override
public String getAgentName() {
return this.name;
}
}
The problem is that you are trying to access the ResultSet after the connection is closed.
You should open and close the connection in the method that is calling run() this way the connection will be open when you access and loop through the Resultset and close it in the finally block of the calling method.
Even better would be if you can just loop through the ResultSet in the run() method and add the data to an object and return the object, this way you can close it in the finally block of the run() method.

Accessing berkeley db from another class in Java

I created a database in one of my java class files and was wondering how to access/open that database in another java class file to read through the data. I tried using openDatabase but how does it know the location of the database file? I've searched through many forums and all I could find is having the code in the same class and just accessing the database object.
ex.I created a database at the directory /documents/ in one of my java class files and all my java code is somewhere else. How do I access and use that database in my other source code?
Edit:
public static void main(String[] args) {
try {
EnvironmentConfig environmentConfig=new EnvironmentConfig();
environmentConfig.setAllowCreate(true);
Environment environment=new Environment(new File("user/documents/"),environmentConfig);
DatabaseConfig databaseConfig=new DatabaseConfig();
databaseConfig.setAllowCreate(true);
Database db=environment.openDatabase(null,"mytable",databaseConfig);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
I tried the following and I keep getting this error when compiling.
openDatabase(com.sleepycat.db.Transaction,java.lang.String,java.lang.String,com.sleepycat.db.DatabaseConfig) in com.sleepycat.db.Environment cannot be applied to (<nulltype>,java.lang.String,com.sleepycat.db.DatabaseConfig)
Database db=environment.openDatabase(null,key,databaseConfig);
^
1 error
Yeah since it is related to mysql database , that means you have to have a password and username as it is a secure school system , and you can use mysql connector to access the data you created .
To be more clear you have to have database.java file .
then in that file the main thing to know is the constructor and way to go ...
import java.sql.*;
public class database
{
public static database bDatabase = null;
protected String connection_url = "";
protected String _name = "";
protected String name = "";
protected String user = "";
protected String password = "";
protected Class some_class = null;
protected Connection connection = null;
protected ResultSet results = null;
protected String current_table = "";
protected Boolean error = false;
public database(String name, String user, String password)
{
this(name, user, password, "jdbc:mysql://localhost:3306", "com.mysql.jdbc.ClassName");
}
public database(String name, String user, String password, String connection_url, String any_name)
{
this.name = name;
this.user = user;
this.password = password;
this.connection_url = connection_url;
this._name = any_name;
}
public static void openDatabase()
{
try
{
bDatabase = new database("dbname", "user_id",
"password", "jdbc:mysql://host",
"com.mysql.jdbc.Anyclass");
bDatabase.open();
}
catch (Exception ex)
{
throw new InvalidQueryException("Unable to open database ");
}
}

Get string value from JFrame to a Java Class

Hello i'm trying to build a small application that will allow me to store email addresses in a MySQL database. What i've done is that i've created a Java Class file (ec.java) and a connection that works fine and code for executing this into the database.
In the JFrame (ecframe.java) have i created a textfield and a button. When typing in the email address and pressing the button it will store this information to a string called textFieldValue. But what i can't figure out is how to get this string into my ec.java file.
This is my code from ec.java:
package emailcollector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ec {
public static void main(String[] args) {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
Statement stmt = (Statement) con.createStatement();
String email = textFieldValue;
String insert = "INSERT INTO emails VALUES ('" + email + ")";
stmt.executeUpdate(insert);
}catch(Exception e) {
}
}
}
And this is my code inside the ecframe.java:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textFieldValue = jTextField1.getText();
JOptionPane.showMessageDialog(this, "Added: \nEmail: " + textFieldValue);
}
Is this because of the "private". It's confusing for me. Thanks in advance!
make con static variable in ec.java, then on ecframe on button action event call the mysql statement, and create the statement by calling the static connection con variable
package emailcollector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ec {
public static Connection con;
public static void main(String[] args) {
try{
con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
}catch(Exception e) {
}
}
}
ecframe.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textFieldValue = jTextField1.getText();
Statement stmt = (Statement) ec.con.createStatement();
String email = textFieldValue;
String insert = "INSERT INTO emails VALUES ('" + email + ")";
stmt.executeUpdate(insert);
}
Instead of making things static, often times I like to make my components independent of one another. In particular, I like the way that JFileChooser and JColorChooser work, so I like to emulate their functionality here by using either a modal JDialog, or a JOptionPane.
For example, here's a simple panel that represents a form that takes an email:
class EmailForm extends JPanel {
private JTextField emailField = new JTextField(20);
public EmailForm() {
add(new JLabel("Email"));
add(emailField);
}
public String getEmail() {
return emailField.getText();
}
}
And in your main method, you'd simply say:
EmailForm form = new EmailForm();
int option = JOptionPane.showConfirmDialog(null, form, "Email", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
System.out.println(form.getEmail());
}
Now, if in your case the form can't be made independent, and the class that holds that database connection represents a context without which the UI cannot function properly, then you might want to occasionally pass a dependency like that to the main form's constructor. Other than that, you can fiddle with actions, event listeners, or even the factory pattern as others have suggested.
There are a number of ways you could achieve this, this is just one (and it's a start of a very BASIC example of a possible Factory pattern)
You need to provide some way so that the ec class can expose its functionality...
Something more like...
public class EmailManager {
private Connection con;
protected Connection getConnection() {
if (connection == null) {
con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
}
return con;
}
public void close() throws SQLException {
if (con != null) {
con.close();
}
con = null;
}
public void insertEmail(String email) throws SQLException {
Statement stmt = null;
try {
Statement stmt = getConnection().createStatement();
int count = stmt.execute("insert into emails values ('" + email + "')");
if (count != 1) {
throw new SQLException("Failed to insert new email");
}
} finally {
try {
stmt.close();
} catch (Exception exp) {
}
}
}
}
Then in your UI class, you simple create an instance of ec and access it's methods as required...
private EmailManager manager;
/*...*/
protected EmailManager getEMailManager() {
if (manager == null) {
manager = new EmailManager();
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textFieldValue = jTextField1.getText();
try {
getEMailManager().insertEmail(textFieldValue);
} catch (SQLException exp) {
JOptionPane.showMessageDialog(this, "Failed to insert email into database", "Error", JOptionPane.ERROR_MESSAGE);
exp.printStackTrace();
}
}
No offense, but all of this is basic OO programming. You might like to take a read through Classes and Objects for more details and ideas
You may also like to take a look at Code Conventions for the Java Programming Language

can we create a common database class in java

i want to know if we can create a common database class same like we create a connection class and just call getConnection when we need connection to be established.
Basically, i want a database manager class which can handle database operation irrespective of tablename, columncount,etc.
tablename, columnname, values to be inserted would be passed as parameters from servlet.
that way, i can reduce duplication of code. m tryin to make a simple mvc application using jsp-servlets. my database is mysql. i dont know struts, spring, hibernate.
For Example, servlet code will call(databaseManager is the class name.) :
int count=databaseManager.getCount("tableName", "columnName", "value");
and in databaseManager, there will be a function -
public static int getCount(String tableName, String[] arrC, objectArray[] arrV)
{}
similarly, for other functions.
i googled and found out that it could be done using metadata.
but i dont know how to use it.
it would be helpful if u could post code of one function for similar approach.
Check DbUtils component of Apache Commons. Also there are examples provided.
Yes, sure you can. I have done something similar (but not the same) and there can be many approaches. I think you should google more, I'm sure, that there are lot of open source applications for database management/database clients. Try to get inspiration there.
Okay, here is some code for inspiration. It is not totally generic, or what are you looking for, but I think, this could lead you somewhere. If not, throw the stone. :-)
Database provider class:
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaProperty;
public class DatabaseProvider<T extends DatabaseObject> {
private static DatabaseProvider databaseProvider;
private static String connectionString = "";
private static String password = "";
private static String username = "";
private static boolean initialized = true;
public DatabaseProvider(){ }
public static void initDatabaseProvider() {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
}
catch(SQLException e){
initialized = false;
e.printStackTrace();
}
connectionString = "XXX";
username = "XXX";
password = "XXX";
}
public List<T> performSimpleSelectQuery(String table, String columns, String where, Class targetObj) throws SQLException {
if(!initialized) return null;
List<T> results = new ArrayList<T>();
Constructor ct;
DatabaseObject dbo;
try {
ct = targetObj.getConstructor(null);
dbo = (DatabaseObject)ct.newInstance(null);
}
catch(Exception e){
e.printStackTrace();
return null;
}
String[] cols = columns.split(",");
String[] properties = new String[cols.length];
for(int i = 0; i < cols.length; i++){
cols[i] = cols[i].trim();
properties[i] = dbo.getMappingFromColumnName(cols[i]);
}
Connection conn = DriverManager.getConnection(connectionString, username, password);
PreparedStatement pst = conn.prepareStatement("SELECT " + columns + " FROM " + table + (where.equals("") ? "" : " WHERE " + where));
pst.execute();
ResultSet rs = pst.getResultSet();
while(rs.next()){
try {
dbo = (DatabaseObject)ct.newInstance(null);
for(int i = 0; i < cols.length; i++){
BeanUtils.setProperty(dbo, properties[i], rs.getObject(cols[i]));
}
results.add((T)dbo);
}
catch(Exception e){
e.printStackTrace();
rs.close();
pst.close();
conn.close();
return null;
}
}
rs.close();
pst.close();
conn.close();
return results;
}
public int performInsert(String columns, String values, String table) throws SQLException {
String sqlInsert = "INSERT INTO " + table + " (" + columns + ") VALUES (" + values + ")";
Connection conn = DriverManager.getConnection(connectionString, username, password);
PreparedStatement pst = conn.prepareStatement(sqlInsert);
int toReturn = 0;
try {
toReturn = pst.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
pst.close();
conn.close();
return toReturn;
}
pst.close();
conn.close();
return toReturn;
}
}
Database object class:
import java.util.HashMap;
public abstract class DatabaseObject {
protected HashMap<String, String> dbToBeanMapping = new HashMap<String, String>();
public DatabaseObject() {
initialize();
}
protected abstract void initialize();
public String getMappingFromColumnName(String columnName) {
return dbToBeanMapping.get(columnName);
}
}
Example class:
public class CounterParty extends DatabaseObject {
private String name;
private int instrument;
private int partyId;
public int getPartyId() {
return partyId;
}
public void setPartyId(int partyId) {
this.partyId = partyId;
}
public CounterParty(){}
public int getInstrument() {
return instrument;
}
public void setInstrument(int instrument) {
this.instrument = instrument;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected void initialize() {
this.dbToBeanMapping.put("company_name", "name");
this.dbToBeanMapping.put("party_id", "partyId");
this.dbToBeanMapping.put("inst_id", "instrument");
}
}

Categories