DAO interfaces

A Data Access Object (DAO) is an interface that provides structured access to databases.

DAO definition

DAOs are defined as interfaces annotated with @Dao.

Implementation classes for the DAO interfaces are automatically generated by the annotation processor during compilation.

Query definition

Queries can be defined using annotations.

You can use Query builders or Unified Criteria API in a Default method when you need to build queries dynamically in Java code.

Default method

You can write Java code freely in default methods.

You can get the Config instance associated with a DAO instance by calling Config.get with the DAO instance as an argument.

@Dao
public interface EmployeeDao {

    default int count() {
        Config config = Config.get(this);
        SelectBuilder builder = SelectBuilder.newInstance(config);
        builder.sql("select count(*) from employee");
        return builder.getScalarSingleResult(int.class);
    }
}

Example

Implementation classes are automatically generated by the annotation processor during compilation. These implementation classes can be directly instantiated and used. However, if the configuration class is managed by a Dependency Injection (DI) container, the DI container should control the instantiation of the implementation classes.

Config config = ...;
EmployeeDao employeeDao = new EmployeeDaoImpl(config);
Employee employee = employeeDao.selectById(1);

By default, the implementation class name is the interface name suffixed with Impl. Please refer to Annotation Processing for information on how to customize the package name and suffix.

A DAO interface does not need to be defined in a one-to-one relationship with an entity class. One DAO interface can handle multiple entity classes.

@Dao
public interface MyDao {

    @Select
    Employee selectEmployeeById(int id);

    @Select
    Department selectDepartmentByName(String name);

    @Update
    int updateAddress(Address address);
}