LuckyLuke
LuckyLuke

Reputation: 49057

How to structure code when connecting to databases

I am developing a program in Java that I will use for registering data. I store the data in a MySQL database. We have not been making "big" programs in my class that uses databases for storage so what we have done is to make an adapter(We usually name it DBAdapter or something) that creates the connection and returns it. Then we have made a database handler class where all the statements are being executed. Then last the controller + view class have a reference to this handler and call whatever methods available.

However, my question is: When dealing with multiple tables and maybe different model data wouldn't it be good to separate the code in the handler into smaller chunks? Such as private classes or other public classes that a "main" handler could have references too? Example: If you make a system for a company that ship goods you probably would have a database that stores data about the goods. Then you would have a handler that has many select-statments for various stuff. You would also have many employees and then you probably want to separate the select-statements for the goods from the select-statements for the employees.

I also wonder if handler/adapter etc. is the correct terminology?

(This is not homework btw. I am making a program that will be a used for registering data for my iPhone app)

Thank you for your time.

Upvotes: 0

Views: 411

Answers (2)

MJB
MJB

Reputation: 9389

While ORM may well be where you head, I'd start with

  • a connection pool
  • implementing a DAO pattern strategy. If you are using Spring, look at JDBCTemplate - it will be pretty easy to convert this to HibernateTemplate, etc.

Upvotes: 0

Laurent Pireyn
Laurent Pireyn

Reputation: 6875

You may want to look into Object-relational mapping libraries for Java, such as OpenJPA or Hibernate. If you'd rather stick to SQL - or like the fine-grained control - you may find Ibatis interesting.

In any case, I wouldn't manage the connections to the DB myself but rely on a connection pool, usually accessed through the DataSource interface.

Upvotes: 1

Related Questions