Data Access Object (Dao) in Java

Data access object (DAO) in Java

The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.

That definition from:
http://en.wikipedia.org/wiki/Data_access_object

Check also the sequence diagram here:
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

Maybe a simple example can help you understand the concept:

Let's say we have an entity to represent an employee:

public class Employee {

private int id;
private String name;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

The employee entities will be persisted into a corresponding Employee table in a database.
A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:

interface EmployeeDAO {

List<Employee> findAll();
List<Employee> findById();
List<Employee> findByName();
boolean insertEmployee(Employee employee);
boolean updateEmployee(Employee employee);
boolean deleteEmployee(Employee employee);

}

Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.

DAO design pattern: where should the database access be implemented?

Connection DB is a very bad place to define such implementation. It is just a link with a specific database thats all. You violate single responsibility rule. Better to implement base generic class for all DAO's and place common logic there.

Also if you will use Hibernate framework, you will not need to work with query strings and Object variables casts.

Data access object application

The Data Access Object is just part of a pattern, an abstraction above the data storage at hand. Since the details of the data storage might change by time (changing from MsSQL to MySQL or Oracle or any NoSQL storages) it is good practice to provide an API to the data, hence the interface usage in Java.

"Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation."

Since the clients will only see the public API of data through the interface, the implementation behind can be changed without any consequence (assuming that those changes adhere to the contract established by the API).

"Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data."

If the client would use a concrete DAO class instead of DAO interfaces then every time when the DAO class is changed and recompiled, the client should be also recompiled. In many cases this is undesirable since you don't want to stop your application and / or you have no control above the client.

On the other hand if the DAO interface remains the same, the classes which implement that interface can be changed / replaced with much bigger degree of freedom.

Note that the DAO interface is just one participant in a design pattern. You have to understand better how DAOs might fit / might not fit in YOUR architecture. You might want to organize data access differently based on your requirements.

One alternative might be using active records or data mappers, etc. But really, there are many different possibilities.

Source:
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

Source:
http://martinfowler.com/eaaCatalog/

How Can a Data Access Object (DAO) Allow Simultaneous Updates to a Subset of Columns?

If you do a DAO.read() operation that returns a bean, then update the bean with the user's new values, then pass that bean to the DAO.update(bean) method, then you shouldn't have a problem unless the two user operations happen within milliseconds of each other. Your question implies that the beans are being stored in the session scope or something like that before passed to the update() method. If that's what you're doing, don't, for exactly the reasons you described. You don't want your bean getting out of sync with the db record. For even better security, wrap a transaction around the read and update operations, then there'd be no way the two users could step on each other's toes, even if user2 submits his changes at the exact same time as user 1.

Read(), set values, update() is the way to go, I think. Keep the beans fresh. Nobody wants stale beans.

Should Data Access Objects (DAO) delegate to other DAOs for readability?

A common thing is to use services to call the different daos' need to inject your data. This seems more logical in this case also because it is in fact business logic and imo it is better to have as little as possible of this in your database layer

What is the best approach to write a data access object (DAO)?

You are mixing a DAO (data access object) and a VO (value object) - also known as a DTO (data transfer object) - in the same class.

Example using an interface for DAO behavior (blammy and kpow might be webservice, oracle database, mysql database, hibernate, or anything meaningful):

public interface UserDTO
{
boolean deleteUser(String userId);
UserVO readUser(String userId);
void updateUser(String userId, UserVO newValues);
}

package blah.blammy;
public class UserDTOImpl implements UserDTO
{
... implement it based on blammy.
}

package blah.kpow;
public class UserDTOImpl implements UserDTO
{
... implement it based on kpow.
}

Example VO:


public class UserVO
{
String firstName;
String lastName;
String middleInitial;

... getters and setters.
}

I prefer to identify the target of the delete using an ID instead of a VO object. Also, it is possible that an update will change the target identified by user ID "smackdown" to have user ID "smackup", so I generally pass an id and a VO.

what is the difference between data access layer and data access object?

Data access object is the dao pattern where the data interaction logic is wrapped (encapsulated) inside the dao objects and the behavior is exposed through dao interfaces. Data access layers is more generic and refers to whole set of infrastructure helping to access the database access. Data access layer may contain dao, driver classes and other data access details.

Is a DAO Only Meant to Access Databases?

DAO's are part of the DAL (Data Access Layer) and you can have data backed by any kind of implementation (XML, RDBMS etc.). You just need to ensure that the project instance is injected/used at runtime. DI frameworks like Spring/Guice shine in this case. Also, your Criteria interface/implementation should be generic enough so that only business details are captured (i.e country name criteria) and the actual mapping is again handled by the implementation class.

For SQL, in your case, either you can hand generate SQL, generate it using a helper library like Spring or use a full fledged framework like MyBatis. In our project, Spring XML configuration files were used to decouple the client and the implementation; it might vary in your case.

EDIT: I see that you have raised a similar concern in the previous question. The answer still remains the same. You can add as much flexibility as you want in your interface; you just need to ensure that the implementation is smart enough to make sense of all the arguments it receives and maps them appropriately to the underlying source. In our case, we retrieved the value object from the business layer and converted it to a map in the SQL implementation layer which can be used by MyBatis. Again, this process was pretty much transparent and the only way for the service layer to communicate with DAO was via the interface defined value objects.

Modelling data and accessing it using the DAO pattern

Would modelling my data across three tables like I suggest above be bad practice/the wrong way to go about this? Is there any benefit in storing score and category in separate tables....?

It's a matter of discussion. In case of score I rather stick this information with the question. On the other hand, the category would be in the separated table since more of the question would share the same category, so it makes a perfect sense.

Shouldn't each DAO object only be concerned with a single table in the database?

Yes, DAO, an object should be concerned with a single source of data - as you say. I would certainly try to avoid any ComplexDao since those classes tend to get more complex and the number of methods increases over the time.

There exist a service layer to combine those results together and provide an output to the controller using the very same service.



Related Topics



Leave a reply



Submit