Skip to main content
Dat 3. semester
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Create a Generic DAO Interface

You probably already have one or more DAO classes with methods such as:

create(...)
read(...)
readAll()
update(...)
delete(...)

If you create several DAO classes, for example:

UserDAO
ProductDAO
OrderDAO

they will often contain the same basic CRUD operations.

Instead of defining the same methods again and again, we can describe the common behaviour using a generic interface.

1. Identify what changes

Consider these two methods:

User read(Integer id);
Product read(Integer id);

The structure is the same, but the entity type changes.

We could replace the entity type with a generic type:

T read(Integer id);

But the type of the ID could also vary. Some entities might use:

Integer
Long
UUID
String

Therefore, introduce another generic type for the ID:

T read(I id);

Here:

T = entity type
I = ID type

For example:

T = User
I = Integer

2. Create the interface

Create a new interface called:

IDAO

in your dao or daos package.

Start with:

public interface IDAO<T, I> {

}

Now add method declarations for the five CRUD operations:

create
read
readAll
update
delete

Think about:

  • Which methods should return T?
  • Which method should return List<T>?
  • Which methods need an ID of type I?
  • Which methods need an entity of type T?

When you are finished, your interface should represent the common CRUD operations that all your DAO classes can implement.

3. Use the interface in a DAO

Choose one of your existing DAO classes and make it implement the interface.

For example, if you have:

public class UserDAO {
}

and User uses an Integer as its ID, change it to:

public class UserDAO implements IDAO<User, Integer> {
}

Your IDE will now tell you which methods must be implemented.

Implement the methods using JPA/Hibernate as you normally would.

4. Try another DAO

Now make another DAO implement the same interface:

public class ProductDAO implements IDAO<Product, Integer> {
}

Notice that the interface stays exactly the same.

Only the generic types change.

Reflection

When you are finished, be prepared to explain:

  • What does T represent?
  • What does I represent?
  • Why do we use two generic types instead of just one?
  • What advantage do we get from having IDAO?
  • Does IDAO contain the implementation of the CRUD operations?
  • Could one DAO implement IDAO<User, UUID> while another implements IDAO<Product, Integer>?

Optional challenge

Can you complete this interface without looking at the solution?

public interface IDAO<T, I> {

    ___ create(___);

    ___ read(___);

    ___ readAll();

    ___ update(___);

    void delete(___);
}