================== DAO interfaces ================== .. contents:: Contents :depth: 3 Data Access Object (DAO) is interface for access to database. Dao definition ================== DAOs are defined as interfaces annotated with ``@Dao``. The implementation classes of the DAO interface are generated by the annotation processor at compile time. Query definition ================== :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. .. _dao-default-method: 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. .. 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 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. .. code-block:: java 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. .. code-block:: java DataSource dataSource = ...; EmployeeDao employeeDao = new EmployeeDaoImpl(dataSource); Employee employee = employeeDao.selectById(1); And also, it can instantiate with ``Connection`` specified explicitly. .. code-block:: java 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. .. code-block:: java @Dao public interface MyDao { @Select Employee selectEmployeeById(int id); @Select Department selectDepartmentByName(String name); @Update int updateAddress(Address address); }