================== DAO interfaces ================== .. contents:: Contents :depth: 4 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 ================== :doc:`query/index` can be defined using annotations. You can use :doc:`query-builder/index` or :doc:`query-dsl` in a :ref:`dao-default-method` when you need to build queries dynamically in Java code. .. _dao-default-method: 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. .. code-block:: java @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. .. code-block:: java 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 :doc:`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. .. code-block:: java @Dao public interface MyDao { @Select Employee selectEmployeeById(int id); @Select Department selectDepartmentByName(String name); @Update int updateAddress(Address address); }