Reputation: 818
I need a Design Pattern that is good for communicating with a Database.
I want an object that is used by different subsystems of the software to communicate with the Database. This object will have all the MySQL queries in functions.
For example:
class DatabaseController
{
getAllUsers()
{
// Access the Database and get all the UserNames.
}
findUserID(String id)
{
// Look in the User Table in MySQL database.
}
findItem(String itemName)
{
// Look in the item's table in MySQL database.
}
}
I was thinking of a Singleton, so that I would provide just one entry point to the DatabaseController.
Is there superior design pattern that will allow other classes to communicate with the DatabaseController and has functionality designed for communicating with Databases?
Different parts of the software will call, for example.
class ItemController
{
findItem(String itemName)
{
DatabaseController.findItem(itemName);
}
}
[EDIT] I am looking for something to write myself, possibly looking at a tutorial, and in Java.
Upvotes: 1
Views: 3156
Reputation: 20329
In the past I have implemented a database 'abstraction' using static classes for the database and it's tables. This has led to a complete mess and loads of work. This is definitely not the way to go.
Since you're using Java, you should look into JPA. Using JPA with a Repository pattern works like a charm. You map your entities (domain models) to database tables and you don't have to write a lot of queries. If you would write queries, you'd write JQL queries. Those are abstract queries and are database agnostic.
Upvotes: 0
Reputation: 135992
Data Access Object is a core J2EE pattern for accessing DB data, see http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Upvotes: 1
Reputation: 22760
Depends on the database I think but check out the Entity Framework and also the Data Repository Pattern.
They are the two I always use on any project involving a database.
I wouldn't use a singleton as a DB pattern. I might us it to store static data coming from a database though.
Upvotes: 3