I'm new to Java and I must make some DAO for my app. However, I don't want to make a DAO for each class (with interface) et override methods. Is it possible to make a DAO extended by all the others, with methods working with all kind of Class ? For example, a DAO that could handle class MyClass and class Foo with a single mehtod getList(). Thank you !
Not that gooed idea, in general, but...
If it is about low-level JDBC (no framework like Hibernate, Spring, etc.), then:
You can make an AbstractDAO class, then your other DAO-classes (UserDAO, ProductDAO, etc.), then you can make a CommonService class that has all those DAO-classes and provides the functions you need.
Example:
abstract class AbstractDAO {
private DataSource dataSource;
protected getDataSource() { // Inject it or hard-coded dataSource
return dataSource;
}
}
public class UserDAO extends AbstractDAO {
public User read(long id) {
// blablabla
return user;
}
public List<User> findAll() {
// blablabla
return users;
}
// and so on...
}
public class ProductDAO extends AbstractDAO {
public Product read(long id) {
// blablabla
return product;
}
public List<Product> findAll() {
// blablabla
return products;
}
// and so on...
}
Then other repositories, and then:
public class CommonService {
private final UserDAO userDAO = new UserDAO();
private final ProductDAO productDAO = new ProductDAO();
// other repositories
public User readUser(long id) {
return userDAO.read(id);
}
public Product readProduct(long id) {
return productDAO.read(id);
}
public List<User> findAllUsers() {
return userDAO.findAll();
}
public List<Product> findAllProducts() {
return productDAO.findAll();
}
}
And if you mean you want to make a generic repository (DAO), again not that good idea, because Spring has already made it in a quite good way (it calls JpaRepository
, eg interface MyRepository extends JpaRepository<User, Long> { }
): Source: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.multiple-modules
But if you want, you can make such a mechanism too, based on something like this (but it will be a cumbersome work to make it work like it does in Spring, for instance; because they are a team of experts who worked day and night to realize such a tremendous project):
public abstract class Repo<T, K> {
public abstract T read(K id);
public abstract List<T> findAll();
}
or
public interface Repo<T, K> {
T read(K id);
List<T> findAll();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.