DAO interfaces
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
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.
@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.
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.
@Dao
public interface MyDao {
@Select
Employee selectEmployeeById(int id);
@Select
Department selectDepartmentByName(String name);
@Update
int updateAddress(Address address);
}