Skip to content

Latest commit

 

History

History
96 lines (62 loc) · 2.56 KB

dao.rst

File metadata and controls

96 lines (62 loc) · 2.56 KB

Dao interfaces

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

Dao is defined as interface annotated @Dao.

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

:doc:`query/index` can be defined using annotation.

You use :doc:`query-builder/index` in default method if you want to build query freely in Java code.

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.

@Dao(config = AppConfig.class)
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 :doc:`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.

@Dao(config = AppConfig.class)
public interface MyDao {

    @Select
    Employee selectEmployeeById(int id);

    @Select
    Department selectDepartmentByName(String name);

    @Update
    int updateAddress(Address address);
}