I'm working on an Android App that use SQLCipher, ORMLite for Android to handle to POJO storing with SQLite and Jackson for parsing.
I'm wondering if there would be a better pattern that the one i'm using (Recommended by stayforit) to get the DAO corresponding to the Entity class given. I have over 30 Entity class and I keep adding some over the time and each time, I have to create a DAO class that looks exactly the same as the previous one. How could I generalize using a generic class?
Here is my DbManager class:
public class DbManager {
private static DbManager instance;
private CipherDbHelper dbHelper;
private SecureSharedPreferences settings;
private DbManager() {
}
private DbManager(Context context, String password) {
SQLiteDatabase.loadLibs(context);
dbHelper = new CipherDbHelper(context, password);
}
public static void init(Context context, String password) {
instance = new DbManager(context, password);
}
public static DbManager getInstance() {
if (instance == null) {
Log.e("DbManager", "DbManager is null");
}
return instance;
}
public <D extends Dao<T, String>, T> D getDAO(Class<T> clz) throws SQLException {
return dbHelper.getDao(clz);
}
}
Here is an example of a recurrent DAO class I need to generate each time I add a POJO entity to my project:
public class CategoriesDAO extends BaseDAO<EntityCategories> {
private static CategoriesDAO instance;
private CategoriesDAO() {
}
public synchronized static CategoriesDAO getInstance() {
if (instance == null) {
instance = new CategoriesDAO();
}
return instance;
}
#Override
public Dao<EntityCategories, String> getDAO() throws SQLException, java.sql.SQLException {
return DbManager.getInstance().getDAO(EntityCategories.class);
}
}
Here is how I use it in an Activity:
CategoriesDAO.getInstance().addOrUpdate(categories);
That's the way I like to use Ormlite DAO's:
CRUDOperator:
public interface CRUDOperator<T> {
void create(T obj);
void update(T obj);
void delete(T obj);
}
Repo:
public interface Repo<T> extends CRUDOperator<T>{
Optional<T> queryForId(Integer id);
ObservableList<T> queryForAll();
...
}
OrmliteRepo:
public class OrmliteRepo<T> implements Repo<T> {
protected Dao<T, Integer> dao;
protected OrmliteRepo(Dao<T, Integer> dao) {
this.dao = dao;
}
public ObservableList<T> queryForAll() throws SQLException {
List<T> results = dao.queryForAll();
return Validators.isNullOrEmpty(results) ? FXCollections.observableArrayList() : FXCollections.observableArrayList(results);
}
public Optional<T> queryForId(Integer id) throws SQLException {
T result = dao.queryForId(id);
return Optional.ofNullable(result);
}
#Override
public void create(T obj) throws SQLException {
dao.create(obj);
}
#Override
public void update(T obj) throws SQLException {
dao.update(obj);
}
#Override
public void delete(T obj) throws SQLException {
dao.delete(obj);
}
}
YourRepo:
public class YourRepo extends OrmliteRepo<YourModel> {
public YourRepo(Dao<YourModel, Integer> dao) {
super(dao);
}
}
RepoService:
public interface RepoService {
<T> Repo<T> get(Class<T> dataClass);
}
BaseRepoService:
public class BaseRepoService implements RepoService {
private RepoFactory repoFactory;
private Map<Class<?>, Repo<?>> repoCache;
public BaseRepoService(RepoFactory repoFactory) {
this.repoFactory = repoFactory;
repoCache = new HashMap<>();
}
#Override
public <T> Repo<T> get(Class<T> dataClass) {
#SuppressWarnings("unchecked")
Repo<T> repo = (Repo<T>) repoCache.get(dataClass);
if (repo == null) {
repo = createRepo(dataClass);
repoCache.put(dataClass, repo);
}
return repo;
}
private <T> Repo<T> createRepo(Class<T> dataClass) {
return repoFactory.createRepo(dataClass);
}
}
RepoFactory:
public interface RepoFactory {
public <T> Repo<T> createRepo(Class<T> dataClass);
}
OrmliteRepoFactory:
public class OrmliteRepoFactory implements RepoFactory {
private DbAccess dbAccess;
private final Map<Class<?>, Supplier<OrmliteRepo<?>>> suppliers;
public OrmliteRepoFactory(DbAccess dbAccess) {
this.dbAccess = dbAccess;
suppliers = new HashMap<>();
suppliers.put(YourModel.class, () -> new YourRepo(getDao(YourModel.class)));
}
private <T> Dao<T, Integer> getDao(Class<T> modelClass) {
return dbAccess.getDaoImplementation(modelClass);
}
#Override
#SuppressWarnings("unchecked")
public <T> OrmliteRepo<T> createRepo(Class<T> dataClass) {
return (OrmliteRepo<T>) suppliers.get(dataClass).get();
}
}
DbAccess:
public interface DbAccess {
<T, R> R getDaoImplemantation(Class<T> dataClass);
}
OrmliteDbAccess:
public class OrmliteDbAccess implements DbAccess{
#Override
public <T, R> R getDaoImplementation(Class<T> objectClass) {
R dao = null;
try {
dao = DaoManager.createDao(connectionSource, objectClass);
} catch (SQLException e) {
LOGGER.error("Error getting dao for class {}; {}", objectClass, e);
}
return dao;
}
}
Now all you need to do is add the suppliers for your repos to the repoFactory and make YourRepo.class extend OrmliteRepo.class. If I need some additional behaviour for a specific repo, I put it in that repo implementation.
When you have an instance of RepoService:
RepoService repoService = new BaseRepoService(ormliteRepoFactory);
you can access your repo like this:
Repo<YourModel> repo = repoService.get(YourModel.class);
You could store the instances of your POJO daos in a map either inside your BaseDao itself or in a subclass and then use an unchecked cast to extract it out.
public class GenericDao<T> extends BaseDao<T> {
private static class InstanceHolder {
static final Map<Class<?>, GenericDao<?>> INSTANCES = new HashMap<>();
}
public static synchronized <T> GenericDao<T> getInstance(Class<T> clazz) {
GenericDao<T> dao = (GenericDao<T>)InstanceHolder.INSTANCES.get(clazz);
if (dao == null) {
dao = new GenericDao<T>();
InstanceHolder.INSTANCES.put(clazz, dao);
}
return dao;
}
private GenericDao() {
}
}
and then
GenericDao<EntityCategories> foo = GenericDao.getInstance(EntityCategories.class);
foo.addOrUpdate(....);
Related
I am creating DTO structure with Builder pattern. Because of existence of many requests I created parent request AbstractRequest to create concrete requests - e.g. ConcreteRequest in this example.
Base Buildable interface defines contract to all Requests.
public interface Buildable<T> {
T build();
void validate();
}
Parent request AbstractRequest to create concrete ConcreteRequest that holds parameters used by all descendants (for brevity globalValue only in this example).
public abstract class AbstractRequest {
private final String globalValue;
public AbstractRequest(BuilderImpl builder) {
this.globalValue = builder.global;
}
public interface Builder<T> extends Buildable<T> {
Builder<T> globalValue(String globalValue);
}
public abstract static class BuilderImpl<T> implements Builder<T> {
private String global;
#Override
public Builder<T> globalValue(String globalValue) {
this.global = globalValue;
return this;
}
}
}
Concrete request that has one private parameter localValue:
public final class ConcreteRequest extends AbstractRequest {
private final String localValue;
public ConcreteRequest(BuilderImpl builder) {
super(builder);
this.localValue = builder.localValue;
}
public String getLocalValue() {
return localValue;
}
public static Builder builder(){
return new BuilderImpl();
}
public interface Builder extends AbstractRequest.Builder<ConcreteRequest> {
Builder localValue(String localValue);
}
public static final class BuilderImpl extends AbstractRequest.BuilderImpl<ConcreteRequest> implements Builder {
private String localValue;
#Override
public ConcreteRequest build() {
this.validate();
return new ConcreteRequest(this);
}
#Override
public void validate() {
// do validation
}
#Override
public Builder localValue(String localValue) {
this.localValue = localValue;
return this;
}
}
}
Q: Why is not ConcreteRequest#getLocalValue accessible while ConcreteRequest#build is available?
I modified my code and it seems it works.
public interface Buildable<T> {
T build();
void validate();
}
Parent class:
public abstract class AbstractRequest {
private final String globalValue;
public AbstractRequest(BuilderImpl builder) {
this.globalValue = builder.global;
}
public String getGlobalValue() {
return globalValue;
}
public interface Builder<B extends Builder, C extends AbstractRequest> extends Buildable<C> {
B globalValue(String globalValue);
}
public abstract static class BuilderImpl<B extends Builder, C extends AbstractRequest> implements Builder<B, C> {
private String global;
#Override
public B globalValue(String globalValue) {
this.global = globalValue;
return (B) this;
}
#Override
public void validate() {
if (global == null) {
throw new IllegalArgumentException("Global must not be null");
}
}
}
}
and
public final class ConcreteRequest extends AbstractRequest {
private final String localValue;
public ConcreteRequest(BuilderImpl builder) {
super(builder);
this.localValue = builder.localValue;
}
public static Builder builder() {
return new BuilderImpl();
}
public String getLocalValue() {
return localValue;
}
public interface Builder extends AbstractRequest.Builder<Builder, ConcreteRequest> {
Builder localValue(String localValue);
}
public static final class BuilderImpl extends AbstractRequest.BuilderImpl<Builder, ConcreteRequest> implements Builder {
private String localValue;
#Override
public Builder localValue(String localValue) {
this.localValue = localValue;
return this;
}
#Override
public ConcreteRequest build() {
this.validate();
return new ConcreteRequest(this);
}
#Override
public void validate() {
super.validate();
if (localValue == null) {
throw new IllegalArgumentException("Local must not be null");
}
}
}
}
And now I can see all methods:
I want to implement Builder pattern for Generic Base class and Sub class stuck at defining Generic type in Base Builder. Here are the classes.
Sub Class:
public class Sub extends Base<T> {
private final String key;
private Sub(Builder builder) {
super(builder);
this.key = builder.key;
}
public static SubBuilder extends Base.BaseBuilder<SubBuilder> {
String key;
public SubBuilder key(String key) {
this.key = key;
return this;
}
#Override
public Sub build() {
return new Sub(this);
}
}
}
Base Class :
public class Base<T> {
private final T type;
protected Base(BaseBuilder<?> build) {
this.type = build.type;
}
//Base Builder
public static class BaseBuilder<B extends BaseBuilder<B>> {
T type; //This is obviously not right because T is not static reference
public B type(T type) {
this.type = type;
return (B)this;
}
public Base build() {
return new Base(this);
}
}
}
As mentioned can't reference T type in BaseBuilder. How to set T using builder here.
Can't remove static from BaseBuilder too.
Is builder pattern suitable for this kind of problems?
Add T type parameter to BaseBuilder, Sub and SubBuilder:
public class Base<T> {
private final T type;
protected Base(BaseBuilder<?, T> build) {
this.type = build.type;
}
public static class BaseBuilder<B extends BaseBuilder<B, T>, T> {
private T type;
public B type(T type) {
this.type = type;
return (B) this;
}
public Base<T> build() {
return new Base<>(this);
}
}
}
public class Sub<T> extends Base<T> {
private final String key;
private Sub(SubBuilder<T> builder) {
super(builder);
this.key = builder.key;
}
public static class SubBuilder<T> extends BaseBuilder<SubBuilder<T>, T> {
private String key;
public SubBuilder<T> key(String key) {
this.key = key;
return this;
}
#Override
public Sub<T> build() {
return new Sub<>(this);
}
}
}
Hello I Have a problem with my Spring/Hibernate project. I was trying to implement generic classes for DAOs and Services and use one concrete implementation to show something on screen. Everything starts without error, but if i wanna create a new project, after form submisions it throws Stack Overflow error (see image below). I rly cant find out where the problem is. I hope someone here can help me. Below you can see all my code, potentialy can add jsp or config files if necessary. Thanks for your time.
GenericDaoImpl
#SuppressWarnings("unchecked")
#Repository
public abstract class GenericDaoImpl<T, PK extends Serializable> implements IGenericDao<T, PK> {
#Autowired
private SessionFactory sessionFactory;
protected Class<? extends T> entityClass;
public GenericDaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
entityClass = (Class<? extends T>) pt.getActualTypeArguments()[0];
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public PK create(T t) {
return (PK) currentSession().save(t);
}
#Override
public T read(PK id) {
return (T) currentSession().get(entityClass, id);
}
#Override
public void update(T t) {
currentSession().saveOrUpdate(t);
}
#Override
public void delete(T t) {
currentSession().delete(t);
}
#Override
public List<T> getAll() {
return currentSession().createCriteria(entityClass).list();
}
#Override
public void createOrUpdate(T t) {
currentSession().saveOrUpdate(t);
}
GenericServiceImpl
#Service
public abstract class GenericServiceImpl<T, PK extends Serializable> implements IGenericService<T, PK>{
private IGenericDao<T, PK> genericDao;
public GenericServiceImpl(IGenericDao<T,PK> genericDao) {
this.genericDao=genericDao;
}
public GenericServiceImpl() {
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return create(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public T read(PK id) {
return genericDao.read(id);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void update(T t) {
genericDao.update(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void delete(T t) {
genericDao.delete(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void createOrUpdate(T t) {
genericDao.createOrUpdate(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<T> getAll() {
return genericDao.getAll();
}
}
ProjectDaoImpl
#Repository
public class ProjectDaoImpl extends GenericDaoImpl<Project, Integer> implements IProjectDao{
}
ProjectServiceImpl
#Service
public class ProjectServiceImpl extends GenericServiceImpl<Project, Integer> implements IProjectService {
#Autowired
public ProjectServiceImpl(#Qualifier("projectDaoImpl") IGenericDao<Project, Integer> genericDao) {
super(genericDao);
}
}
ProjectController
public class ProjectController {
#Autowired(required = true)
private IProjectService projectService;
#RequestMapping(value = "/projects", method = RequestMethod.GET)
public String listProjects(Model model){
model.addAttribute("project", new Project());
model.addAttribute("listProjects", projectService.getAll());
return "project";
}
//for add and update role both
#RequestMapping(value = "/project/add", method = RequestMethod.POST)
public String addProject(#ModelAttribute("project") Project p){
if( p.getId() == 0){
//new role, add it
projectService.create(p);
} else {
//existing role, call update
projectService.update(p);
}
return "redirect:/projects";
}
#RequestMapping("/remove/{id}")
public String deleteProject(#PathVariable("id") int id){
projectService.delete(projectService.read(id));
return "redirect:/projects";
}
#RequestMapping("edit/{id}")
public String editProject(#PathVariable("id") int id, Model model){
model.addAttribute("project", projectService.read(id));
model.addAttribute("listProjects", projectService.getAll());
return "project";
}
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return create(t);
}
This method is calling itself unconditionally. This can only result in a StackOverflowError.
Did you mean to do this?
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return genericDao.create(t);
}
I want to write abstract class, which will contains all generic methods for working with db like save, update and etc. After that create as many implementations as many DAO's I need, and, if needed, overwrite/add methods.
public interface Dao<T, ID extends Serializable> {
void save(T t);
T get(ID id);
void update(T t);
void remove(T t);
List<T> findAll();
}
#Repository
#Transactional
public abstract class AbstractDao<T, ID extends Serializable> implements Dao<T, ID> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> clazz;
public AbstractDao(Class<T> clazz) {
this.clazz = clazz;
}
public void save(T t) {
sessionFactory.getCurrentSession().save(t);
}
public T get(ID id) {
return sessionFactory.getCurrentSession().get(clazz, id);
}
public void update(T t) {
sessionFactory.getCurrentSession().update(t);
}
public void remove(T t) {
sessionFactory.getCurrentSession().delete(t);
}
public List<T> findAll() {
return sessionFactory.getCurrentSession().createCriteria(clazz).list();
}
}
#Repository
#Transactional
public class UserDao extends AbstractDao<User, Integer> {
public UserDao() {
super(User.class);
}
}
public class MainTest {
#Test
public void testName() throws Exception {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HibernateConfig.class);
UserDao userDao = ctx.getBean(UserDao.class);
...
}
}
And I get this error:
No qualifying bean of type [com.sevak-avet.UserDao] is defined
If I don't use AbstractDao class and implement all methods directly in UserDao, it works. What I'm doing wrong?
I run in few huge problems by using getSession() on HibernateDaoSupport and now when i try to fix it I was wondering if it is right to make a abstract class like this bellow and make all Dao's to extend it instead of adding SessionFactory in each Dao ?
If it is, then would creating bean of this abstract Dao class and passing it the session factory then work once other Dao's extend it? Or that is not even possible?
public abstract class AbstractDAOImpl<T> implements
AbstractDAO<T> {
private static Logger _logger = LoggerFactory
.getLogger(AbstractDAOImpl.class);
private SessionFactory factory;
#Override
public void refresh(final T object) {
try {
factory.getCurrentSession().refresh(object);
} catch (Exception e) {
_logger.error("Cannot refresh object " + object, e);
}
}
#Override
public void remove(final T object) {
try {
factory.getCurrentSession().delete(object);
} catch (Exception e) {
_logger.error("Cannot remove object " + object, e);
}
}
#Override
public void save(final T object) {
try {
factory.getCurrentSession().saveOrUpdate(object);
} catch (Exception e) {
_logger.error("Cannot save or update object " + object, e);
}
}
}
public interface RootDAO<T> extends Serializable {
public List<T> loadAll();
public T save(T entity);
public void delete(T entity);
public void markAsDeleted(T entity);
public T get(Serializable id);
public T load(Serializable id);
public void saveOrUpdate(T entity);
public void deleteAll(Collection<T> entities);
public void saveOrUpdateAll(Collection<T> entities);
public List<T> find(String hql);
public void update(T entity);
public T getByExampleUnique(T entity);
public List<T> getByExampleList(T entity);
public List<T> listAll();
public Object execute(HibernateCallback action);
public List<T> findByNamedParam(String queryString, String paramName,Object value);
public List<T> findByNamedParam(String queryString, String[] paramNames,Object[] values);
.
.
.
.
}
#Component
public abstract class RootDAOImpl<T> extends HibernateDaoSupport implements RootDAO<T> {
protected Logger logger = LoggerFactory.getLogger(getClass());
private Class<T> clazz;
#Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
public RootDAOImpl(Class<T> clazz) {
this.clazz = clazz;
}
public void delete(T entity) {
getHibernateTemplate().delete(entity);
}
public void delete(String id) {
getHibernateTemplate().delete(new FbUser(id));
}
public void markAsDeleted(T entity) {
// Mark entity as deleted
try {
Method setDeletedMethod = clazz.getDeclaredMethod("setDeleted", Boolean.class);
setDeletedMethod.invoke(entity, true);
getHibernateTemplate().saveOrUpdate(entity);
} catch (Exception e) {
e.printStackTrace();
}
// actually delete
// getHibernateTemplate().delete(entity);
}
#Override
public void deleteAll(Collection<T> entities) {
getHibernateTemplate().deleteAll(entities);
}
#Override
public void saveOrUpdateAll(Collection<T> entities) {
getHibernateTemplate().saveOrUpdateAll(entities);
}
#SuppressWarnings("unchecked")
#Override
public T get(Serializable id) {
return (T) getHibernateTemplate().get(clazz, id);
}
#SuppressWarnings("unchecked")
#Override
public T load(Serializable id) {
return (T) getHibernateTemplate().load(clazz, id);
}
#SuppressWarnings("unchecked")
#Override
public List<T> find(String hql) {
return (List<T>) getHibernateTemplate().find(hql);
}
#Override
public Object execute(HibernateCallback action) {
return getHibernateTemplate().execute(action);
}
.
.
.
}
#Repository
public class UserDAOImpl extends RootDAOImpl<User> implements UserDAO{
public UserDAOImpl() {
super(User.class);
}
}
If you are not using a DI framework you may need to keep a reference for SessionFactory and pass it yourself when you create the DAO instance.
This is exactly why people use JPA implementation by hibernate. You just need to start using the JPA's EntityManager which leverages on SessionFactory by itself in the best possible design patterns. You dont have to reinvent the whole design patterns here. All you need to do is just use CRUD operations of EntityManager in each of your DAO as shown in the following example. All the best with your implementation.
http://www.myhomepageindia.com/index.php/2009/04/02/jpa-hibernate-with-oracle-on-eclipse.html