Dao interfaces

Data Access Object (Dao) is interface for access to database.

Dao definition

Dao is defined as interface annotated @Dao.

Class implemented dao interface is generated in compile time by apt.

Query definition

Queries can be defined using annotation.

You use Query builders in default method if you want to build query freely in Java code.

Default method

You can write java code freely in default method.

You can get Config instance associated dao instance if you call Config.get with argument dao instance.

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);


Implementation class is generated by annotation processor on compile. Implementation class is instantiated and used. But if configuration class is managed by DI container then it should be controlled to instantiate implementation class by DI container.

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

In default, implementation class name is interface name suffixed with Impl. Please refer Annotation processing to change package and suffix.

If you use default constructor then DataSource is determined by configuration in config element of @Dao. But it can instantiate with DataSource specified explicitly.

DataSource dataSource = ...;
EmployeeDao employeeDao = new EmployeeDaoImpl(dataSource);
Employee employee = employeeDao.selectById(1);

And also, it can instantiate with Connection specified explicitly.

Connection connection = ...;
EmployeeDao employeeDao = new EmployeeDaoImpl(connection);
Employee employee = employeeDao.selectById(1);

Dao interface is no need to define as one to one with entity class. One dao interface can handle more than one entity classes.

public interface MyDao {

    Employee selectEmployeeById(int id);

    Department selectDepartmentByName(String name);

    int updateAddress(Address address);