how to implement generic spring jpa repository for all entities - java

I have other BaseDaoImpl which is already generic but i want to add PaginationandSortiongRepository as generic, Please Help to Implement
I have tried every way to add GenericJPADAO as bean but its not possible is there, Is there any other way to implement?
public interface BaseDao<T, ID extends Serializable> {
public List<T> findAll();
public T findOne(final long id);
public T update(T object);
public T get(Long id);
public void delete(T object);
public void insert(T object);
public boolean exists(Long id);
T getByCondition(String fieldName, Object value);
List<T> getALL();
}
public class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> {
#PersistenceContext
protected EntityManager entityManager;
private Class<T> entityType;
public BaseDaoImpl() {
this.entityType = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
#Override
#Transactional
public void insert(T entity) {
entityManager.persist(entity);
}
#Transactional
public List<T> findAll() {
return entityManager.createQuery("from " + entityType.getName()).getResultList();
}
#Override
#Transactional
public T findOne(long id) {
return entityManager.find(entityType, id);
}
#Override
#Transactional
public T update(T entity) {
return entityManager.merge(entity);
}
#Override
#Transactional
public T get(Long id) {
// TODO Auto-generated method stub
return entityManager.find(entityType, id);
}
#Override
#Transactional
public void delete(T object) {
entityManager.remove(object);
}
#Override
#Transactional
public boolean exists(Long id) {
return entityManager.contains(id);
}
#Override
#Transactional
public T getByCondition(String fieldName, Object value) {
System.out.println(entityType);
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<T> criteria = cb.createQuery(entityType);
Root<T> member = criteria.from(entityType);
criteria.select(member).where(cb.equal(member.get(fieldName), value + ""));
List<T> results = entityManager.createQuery(criteria).getResultList();
if (results.isEmpty()) {
return null;
} else {
return (T) results.get(0);
}
}
#Override
public List<T> getALL() {
return null;
}}
#NoRepositoryBean
public interface GenericJpaDao<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
enter code here
}
#Repository
public class AccountDaoImpl extends BaseDaoImpl<Account, Long> implements AccountDao {
/* Not able to Inject If add #Repository on GenericJapDao, How to Implement As generic Same as BaseDaoImpl*/
GenericJpaDao< Account, Long> generiCJPADao;
#Override
public Account getAccount(String emailAddress) {
return getByCondition("emailAddress", emailAddress);
}
#Override
public void saveAccount(Account account) {
insert(account);
}}
Not able to add GenericJPA and i am not sure how to make Repository as Generic,
Thnaks in Advance

Related

How to generify my interface

I have the following interface:
public interface ProvidersFilter {
void setQuery(#NonNull Object query);
Object apply();
}
And the following implementing classes:
First implementation:
public class ProvidersRemoteFilter implements ProvidersFilter {
private Query mQuery;
#Override
public void setQuery(#NonNull Object query) {
if (query instanceof Query) {
mQuery = (Query) query;
} else {
throw new RuntimeException("query object must be of type com.google.firebase.firestore.Query");
}
}
#Override
public Object apply() {
return mQuery;
}
}
Second implementation:
public class ProvidersLocalFilter implements ProvidersFilter {
private String mQuery;
#Override
public void setQuery(#NonNull Object query) {
if (query instanceof String) {
mQuery = (String) query;
} else {
throw new RuntimeException("query object must be of type String");
}
}
#Override
public Object apply() {
return mQuery;
}
}
I would like to avoid using instanceof by generifying my interface and implementing classes.
You need to add a type variable to your interface.
Interface:
public interface ProvidersFilter<T> {
void setQuery(#NonNull T query);
T apply();
}
Implementing class:
public class ProvidersRemoteFilter implements ProvidersFilter<Query> {
private Query mQuery;
#Override
public void setQuery(#NonNull Query query) {
mQuery = query;
}
#Override
public Query apply() {
return mQuery;
}
}
Since local and remote Providers have the same code you could have an abstract class that implements the commonalities. In that case there is no need for the interface but you can keep it all the same:
public interface ProvidersFilter<Q> {
void setQuery(#NonNull Q query);
Q apply();
}
abstract class AbstractProvidersFilter<Q> {
private Q mQuery;
#Override
public void setQuery(#NonNull Q query) {
mQuery = query;
}
#Override
public Q apply() {
return mQuery;
}
}
public class ProvidersRemoteFilter extends AbstractProvidersFilter<Query> {}
public class ProvidersLocalFilter extends AbstractProvidersFilter<String> {}

How to implement GenericDAO class on Hibernate

I want UserDao class to extend GenericDAO where i'll have all CRUD methods. I have read article from IBM: http://www.ibm.com/developerworks/java/library/j-genericdao/index.html , but i could not implement it. Could someone show me example based on my custom UserDao class.
#Transactional(value="myTransactionManager")
public class UserDao {
#Qualifier("mySessionFactory")
public SessionFactoryImpl sessionFactory;
public void setSessionFactory(SessionFactoryImpl sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<UserEntity> getAll() {
Query query = sessionFactory.getCurrentSession().createQuery(
"from UserEntity ");
List<UserEntity> userList = query.list();
return userList;
}
public void updaet(UserEntity userEntity) {
sessionFactory.getCurrentSession().update(userEntity);
}
public void delete(UserEntity userEntity) {
sessionFactory.getCurrentSession().delete(userEntity);
}
public void save(UserEntity userEntity) {
sessionFactory.getCurrentSession().save(userEntity);
}
}
i tried to write class like this
public class GenericDao{
#Qualifier("mySessionFactory")
public SessionFactoryImpl sessionFactory;
public void setSessionFactory(SessionFactoryImpl sessionFactory) {
this.sessionFactory = sessionFactory;
}
public <T> List<T> getAll(Class<T> t) {
Query query = sessionFactory.getCurrentSession().createQuery(
"from " + t.getName());
List<T> list = query.list();
return list;
}
public <T> void save(T t) {
sessionFactory.getCurrentSession().save(t);
}
public <T> void update(T t) {
sessionFactory.getCurrentSession().update(t);
}
public <T> void delete(T t) {
sessionFactory.getCurrentSession().delete(t);
}
}
but when i try to pull data with UserDao like this:
public List<UserEntity> getAll() {
List<UserEntity> list = UserDao.findAll();
}
Eclipse IDE for line List<UserEntity> list = UserDao.findAll(); give error : The method findAll() is underfined for type UserDao.
this is my implementation :
GenericDao :
#Repository
public class GenericDao<T extends DbObject> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> getParameterizedClass() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public T findById(final Serializable id) {
return (T) getCurrentSession().get(getParameterizedClass(), id.toString());
}
public void persist(final T object) {
getCurrentSession().persist(object);
}
public void saveOrUpdate(final T object) {
getCurrentSession().saveOrUpdate(object);
}
public void delete(final T object) {
getCurrentSession().delete(object);
}
public T merge(final T object) {
return (T) getCurrentSession().merge(object);
}
}
UserDao :
public class UserDao extends GenericDao<User> {
}
Entity :
#Entity
#Table(name = "...")
public class User extends DbObject {
}

Implement a generic interface

I have a generic interface and I would like to implement this interface in a generic way :
public interface BaseBean<T> {
public T create(T t);
public T read(Long id);
public T update(T t);
public void delete(T t);
}
For some reason, I can't make the implementation generic as well. Eclipse implements all interface methods in non-generic way:
public class BaseBeanImpl<T> implements NewBaseBean {
#Override
public Object create(Object t) {
return null;
}
#Override
public Object read(Long id) {
return null;
}
#Override
public Object update(Object t) {
return null;
}
#Override
public void delete(Object t) {
}
#Override
public Object find(Long id) {
return null;
}
}
When I change:
public Object create(Object t)
to
public T create(T t)
I get a compile error. Did I miss something?
Change
public class BaseBeanImpl<T> implements NewBaseBean
to
public class BaseBeanImpl<T> implements NewBaseBean<T>
When you use the raw type NewBaseBean, you get Object instead of T in your interface's methods.
public class BaseBeanImpl<T> implements NewBaseBean<T> {
#Override
public T create(T t) {
return null;
}
#Override
public T read(Long id) {
return null;
}
#Override
public T update(T t) {
return null;
}
#Override
public void delete(T t) {
}
#Override
public T find(Long id) {
return null;
}
}

Apache CXF with Parameterized types

I have a bunch of classes that all look the same and consist merely of an Id and a few String attributes. So I tried to generalize the creation of WebServices using Generics:
#WebService
public interface IBasicCRUDService<E extends AbstractEntity, D extends AbstractEntityDTO, ID, DAO extends IGenericDAO<E, ID>>{
public List<D> findAll(BasicFilters filters);
public D findById(ID id);
#WebMethod(exclude = true)
public void setBaseDao(DAO dao);
}
Implementation:
public abstract class BasicCRUDService<E extends AbstractEntity, D extends AbstractEntityDTO, ID, DAO extends IGenericDAO<E, ID>> extends AbstractService implements IBasicCRUDService<E, D, ID, DAO> {
private IGenericDAO<E, ID> dao;
private Class<E> persistentClass;
private Class<D> dataTransferClass;
public final DAO getDao() {
return (DAO) dao;
}
public void setDao(DAO dao) {
this.dao = (IGenericDAO<E, ID>) dao;
}
#SuppressWarnings("unchecked")
public Class<E> getPersistentClass() {
if (persistentClass == null) {
this.persistentClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
return persistentClass;
}
#SuppressWarnings("unchecked")
public Class<D> getDataTransferClass() {
if(dataTransferClass == null) {
this.dataTransferClass = (Class<D>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
return dataTransferClass;
}
#Override
#Transactional(readOnly=true)
#WebMethod(operationName="findAll")
public List<D> findAll(BasicFilters filters) {
List<E> pList = dao.findAll(filters);
List<D> dList = new ArrayList<D>();
for(E e:pList) {
dList.add(this.map(e, getDataTransferClass()));
}
return dList;
}
#Override
#Transactional(readOnly=true)
#WebMethod(operationName="findAll")
public D findById(ID id) {
return this.map(dao.findById(id), getDataTransferClass());
}
}
And this would be a concrete implementation:
#Service("metodologiaService")
public class MetodologiaService extends BasicCRUDService implements IMetodologiaService {
#Override
#Autowired
#Qualifier("metodologiaDAO")
public void setBaseDao(IMetodologiaDAO dao) {
super.setDao(dao);
}
}
#WebService
public interface IMetodologiaService extends IBasicCRUDService<Metodologia, MetodologiaDTO, Integer, IMetodologiaDAO>{
public List<MetodologiaDTO> findAll(BasicFilters filters);
public MetodologiaDTO findById(Integer id);
}
The problem is when doing it like this it seems CXF is unable to properly map the attributes of the WebServices. For instance, when calling the findById method, I get this:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to java.lang.Integer</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
However, if I declare the methods directly in my IMetodologiaService, it works:
#WebService
public interface IMetodologiaService extends IBasicCRUDService<Metodologia, MetodologiaDTO, Integer, IMetodologiaDAO>{
public List<MetodologiaDTO> findAll(BasicFilters filters);
public MetodologiaDTO findById(Integer id);
}
So it seems somehow extending interfaces is not working when using Parameterized types. Is there any way around this?

Creating a generic DAO for JPA that I can inherit from

I am trying to create a repository class that I can inherit from to get basic CRUD functionality from. The EntityManager.find(..) needs a Class argument. However, you can't pass T to it (By some reason I don't understand yet...type erasure). So I found the method that returns the entity class and added it from another question I saw. First of all, how does it work and second would it have much impact on performace? I see it use reflection.
#Stateless
public abstract class AbstractSqlRepository<T> implements Repository<T> {
#PersistenceContext
private EntityManager entityManager;
#Override
public void create(T entity) {
entityManager.persist(entity);
}
#Override
public T find(int id) {
return entityManager.find(getEntityClass(), id);
}
#Override
public T update(T entity) {
return entityManager.merge(entity);
}
#Override
public void remove(T entity) {
entityManager.remove(entity);
}
public EntityManager getEntityManager() {
return entityManager;
}
public Class<T> getEntityClass() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
return (Class<T>) genericSuperclass.getActualTypeArguments()[0];
}
}
New approach:
#Stateless
public abstract class AbstractSqlRepository<T> implements Repository<T> {
#PersistenceContext
private EntityManager entityManager;
private Class<T> clazz;
public AbstractSqlRepository(Class<T> clazz) {
this.clazz = clazz;
}
#Override
public void create(T entity) {
entityManager.persist(entity);
}
#Override
public T find(int id) {
return entityManager.find(clazz, id);
}
#Override
public T update(T entity) {
return entityManager.merge(entity);
}
#Override
public void remove(T entity) {
entityManager.remove(entity);
}
public EntityManager getEntityManager() {
return entityManager;
}
}
and
public class QuestionSqlRepository extends AbstractSqlRepository implements QuestionRepository {
public QuestionSqlRepository() {
super(Question.class);
}
}
Is this a bad approach?
It is stated that reflection will add overhead but you don't have to get the Class of the object every time in my opinion.
Just find it the first time and check for null afterwards, this adds very little overhead compared to call a super class method.
The only argument against the constructor parameter is that your class won't be a POJO.
Here is the sample code:
#SuppressWarnings("unchecked")
public class HibernateBaseDao<T, Pk extends Serializable> implements Dao<Pk, T> {
// ...
private Class<T> type;
// ...
public Class<T> getType() {
if (this.type == null) {
ParameterizedType parameterizedType = (ParameterizedType) (this
.getClass().getGenericSuperclass());
while (!(parameterizedType instanceof ParameterizedType)) {
parameterizedType = (ParameterizedType) parameterizedType
.getClass().getGenericSuperclass();
}
this.type = (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
return this.type;
}
#Override
public T load(Pk id) {
return (T) this.sessionFactory.getCurrentSession().load(this.getType(),
id);
}
#Override
public T get(Pk id) {
return (T) this.sessionFactory.getCurrentSession().get(this.getType(),
id);
}
}

Categories

Resources