I am currently using Layered Architecture in my (small) project and thought about extending my BaseRepository (the one the class-specific repositories inherit from) using reflection for the insert/update/delete methods.
My BaseRepository.java
looks like this:
public abstract class BaseRepository<CLASS extends BaseDomain<CLASS>>{
}
Where BaseDomain
is just:
public class BaseDomain<CLASS extends BaseDomain<CLASS>> {
private Long id;
//getters setts etc.
}
Now my problem is in the deleteById method in the BaseRepository:
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;
}
My specific repository extends the Base one like this:
public class UserRepository extends BaseRepository<User>{
}
How do I get the User
class in the BaseRepository
so I can use it in the delete/update etc. methods?
Thanks for any help!
How about making the entity be a param to the BaseRepository constructor.
EDIT:
public class UserRepository extends BaseRepository<User>{
public static final String ENTITY = "users";
public UserRepository(){
super(ENTITY);
}
}
A simple way I can think but I haven't tried is to pass the entity class type to the BaseRepository
.
private final Class<CLASS> entityType;
public BaseRepository(Class<CLASS> entityType) {
this.entityType = entityType;
// do your stuff
}
To find the right table to operate according to the entity class type. Could be by convention like most of Ruby ORMs do, say, if the entity type is User
, then you can operate against users
or user
or whatever the convention is.
Or could have a object to provide the configuration to BaseRepository
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.