I want to make a class that can interact with a database, which has the following desired functionality:
- It has a method to return all fields from the database, later can be changed such that it can also limit with it returns.
- It has a method to insert a specific instance of this class.
- It has a method to update a specific instance of this class. I will show the code in a moment after further explanation.
Now I want to extract an interface, or rather an abstract class I think might be more appriopiate, to be sure that all classes/datafields follow the same 'interface', and to be able to use them as a supertype in Lists etc.
The data class, in this case Account.java, should represent a table in a database which stores {Username, Password}, I am omitting an explicite unique identifier for now, still not sure if I will make an additional ID field or use the uniqueness of the Username field.
It would be best if the abstract class itself would handle all the MySQL interaction 'mess'.
Account.java so far:
package testthing; import java.util.Map; /** * * @author Frank */ public class Account { private final static String ALL_QUERY = "SELECT * FROM accounts"; private final static String INSERT_QUERY = "INSERT INTO accounts (username, password) VALUES(?, ?)"; private final static String UPDATE_QUERY = "UPDATE accounts SET password=? WHERE username=?"; private String username; private String password; public Account(final String username, final String password) { this.username = username; this.password= password; } public String getUsername() { return username; } public void setUsername(final String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } public static Map<String, Account> getAll() { //return a map using the ALL_QUERY string } public void insert() { //insert this using INSERT_QUERY } public void update() { //update this using UPDATE_QUERY } } I know that I haven't been that clear I'm afraid, but I hope this is enough to help me get going.
Basically I want to always be able to use the followings methods when working with a TableObject, which Account would be a subset of:
Account.getAll();new Account("test", "test").insert();currentAccount.setPassword("newPassword"); currentAccount.update();
All the nasty SQL stuff should be hidden inside the proposed abstract class. The only thing you cannot escape in a TableObject class is the definition of the SQL queries.
Regards.
EDIT: In current example Account.getAll() returns a Map<String, Account>, but in reality the first generic argument should be the type of the key in the database. So if you would use an unique ID then it would need to return a Map<Integer, Account>. I hope this change makes it in time for people to read it.