我目前在我的(小型)项目中使用分层架构,并考虑使用插入/更新/删除方法的反射来扩展我的 BaseRepository(特定于类的存储库继承的那个)。
我的BaseRepository.java
看起来像这样:
public abstract class BaseRepository<CLASS extends BaseDomain<CLASS>>{
}
其中 BaseDomain
只是:
public class BaseDomain<CLASS extends BaseDomain<CLASS>> {
private Long id;
//getters setts etc.
}
现在我的问题出在 BaseRepository 中的 deleteById 方法中:
public int deleteById(Connection connection, Long id) throws SQLException {
PreparedStatement delete= connection.prepareStatement("DELETE FROM ? WHERE id = ?");
delete.setObject(1, entity) //heres the problem, where do I get entity from?
delete.setObject(2, id);
return 0;
}
我的特定存储库扩展了基础存储库,如下所示:
public class UserRepository extends BaseRepository<User>{
}
如何在 BaseRepository
中获取 User
类,以便我可以在删除/更新等方法中使用它?
感谢您的帮助!
最佳答案
我能想到但没有尝试过的一个简单方法是将实体类类型传递给BaseRepository
。
private final Class<CLASS> entityType;
public BaseRepository(Class<CLASS> entityType) {
this.entityType = entityType;
// do your stuff
}
根据实体类类型找到合适的表进行操作。按照惯例,就像大多数 Ruby ORM 所做的那样,比如说,如果实体类型是 User
,那么您可以针对 user
或 user
进行操作,或者无论约定是什么。
或者可以有一个对象来向BaseRepository
提供配置
关于java - 分层架构 - 存储库和反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47237920/