Reputation: 20555
I am about to create a project where I want to have a class that connects my application to a database.
I want to do this in the best object-orientated way, following the Solid principles!
My question to you is:
Is it ever smart to divide your Provider into subclasses, for example a subclass that gets information from the database and a subclass that can insert data into the database? Or do you keep these functionalities in one huge class?
Upvotes: 0
Views: 819
Reputation: 308938
I'd recommend that you take a look at Martin Fowler's Patterns of Enterprise Application Architecture. He's got a nice chapter on patterns for persistence.
This problem has been solved many, many times: ORM solutions like JPA and Hibernate, iBatis mapping, Spring JDBC. I can't imagine how you'll improve on what's been done before. If you can't articulate what's different, I'd recommend using something that's been written, tested, and proven before investing in something new.
If you must, I'd recommend a generic DAO. Here's a very simple one:
package persistence;
public interface GenericDao<K, V> {
V find(K key);
List<V> find();
K save(V value);
void update(V value);
void delete(V value);
}
Upvotes: 3
Reputation:
I don't agree that ORM is always the way to go.
If you want to programm close to the database, a query mapper like mybatis is a useful alternative to the ORM approach.
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.
mybatis is supported by Spring which makes your live much easier.
Upvotes: 3
Reputation: 3063
Usually it's better to split these classes by Object (i.e. Customer, Client, Car) rather than functionality (i.e. read write). This is the approach that ORM uses, for java specifically take a look at the Hibernate ORM Framework
http://docs.jboss.org/hibernate/orm/3.5/api/
docs above, you can no doubt find good tutorials on google
Upvotes: 1
Reputation: 16060
You could start by reading up on the DAO pattern. Once you have that down, delve further into ORM frameworks.
The short answer: Yes, by all means keep persistence code for specific objects/classes together.
Cheers,
Upvotes: 1