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?
Related
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
I am trying to use inheritence and generics to create my application, but it doesn't seem to work the way I expect it to. I'll show you what I mean (TL;DR at the bottom):
public interface IModel extends Serializable {
public int save();
public void update();
public void delete();
}
// <T> is a JPA annotated entity/class
#SuppressWarnings("serial")
public abstract class Model<T> implements IModel {
private final Repository<T> _repository;
protected T _entity;
public Model(T entity, Repository<T> repository) {
this._entity = entity;
this._repository = repository;
}
public int save() {
return _repository.save(_entity);
}
...
}
This is implemented in for example my AccountModel, which is a Model with generic Account (which is a JPA entity) and which implements IAccount.
public class AccountModel extends Model<Account> implements IAccount {
private static final AccountRepository REPOSITORY = new AccountRepository();
public AccountModel(Account entity) {
super(entity, REPOSITORY);
}
// Method implementations...
}
My generic Repository looks like this:
public abstract class Repository<T> implements Serializable {
private static SessionFactory SESSION_FACTORY;
private final Class<T> _repositoryClass;
private static boolean _initiated = false;
public Repository(Class<T> repositoryClass) {
if (!Repository._initiated)
setup();
this._repositoryClass = repositoryClass;
}
private void setup() {
// logics
Repository._initiated = true;
}
public final Model<T> getById(int id) {
Session session = SESSION_FACTORY.openSession();
try {
session.beginTransaction();
T t = session.get(_repositoryClass, id);
return new Model<T>(t, this); // As suggested by #Vlad
}
finally {
session.close();
}
}
}
The account implementation of this abstract Repository is:
public class AccountRepository extends Repository<Account> {
public AccountRepository() {
super(Account.class);
}
public Model<Account> getByEmail(String emailAddress) {...}
}
So far so good, this is all working as expected. But I cannot use a Model<T> as a TModel.
TL;DR
I would like use the following line of code:
AccountModel account = new AccountRepository().getById(1);
Since AccountModel inherits Model<Account> and new AccountRepository().getById() always returns Model<Account> I expect this to work, but it doesn't.
What am I missing?
Background
Here is my working (simplified) GenericDao interface, which is implemented by any DomainDao:
GenericDao.java
#NoRepositoryBean
public interface GenericDao<E extends Persistable<K>, K extends Serializable> extends JpaRepository<E, K> {
public List<E> findAll();
public E persist(E entity);
}
GenericDaoImpl.java
public class GenericDaoImpl<E extends Persistable<K>, K extends Serializable> extends SimpleJpaRepository<E, K> implements GenericDao<E, K> {
private final JpaEntityInformation<E, ?> entityInformation;
private final EntityManager em;
private final Class<E> type;
public GenericDaoImpl(JpaEntityInformation<E, ?> entityInformation, EntityManager em) {
super(entityInformation, em);
this.entityInformation = entityInformation;
this.em = em;
this.type = entityInformation.getJavaType();
}
#Override
public List<E> findAll() {
return super.findAll();
}
#Override
#Transactional
public E persist(E entity) {
if (entityInformation.isNew(entity) || !EntityUtils.isPrimaryKeyGenerated(type) && !em.contains(entity)) {
em.persist(entity);
}
return entity;
}
}
For example, to manage the domains Foo and Bar, you just need to create two interfaces as follow:
FooDao.java
public interface FooDao extends GenericDao<Foo, Integer> {
}
BarDao.java
public interface BarDao extends GenericDao<Bar, Integer> {
}
The #Autowired annotation of Spring will automatically instantiate a GenericDaoImpl with the good entity and primary key types.
Problem
I'm now trying to add a caching process on my DAOs, using EhCache and the EhCache Spring Annotations model.
GenericDao.java
#NoRepositoryBean
public interface GenericDao<E extends Persistable<K>, K extends Serializable> extends JpaRepository<E, K> {
#Cacheable(cacheName = "dao")
public List<E> findAll();
#TriggersRemove(cacheName = "dao")
public E persist(E entity);
}
applicationContext.xml
<ehcache:annotation-driven cache-manager="ehCacheManager" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
ehcache.xml
<cache name="dao"
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
timeToIdleSeconds="86400"
timeToLiveSeconds="86400"
memoryStoreEvictionPolicy="LFU" />
The problem with the use of a GenericDao, is that the cache should manage each DomainDao independently of each other. For example, with the current configuration, if I call fooDao.findAll(), and then barDao.persist(new Bar()), the cache generated by fooDao.findAll() will be reset, since the same cache would have been used (i.e. <cache name="dao" />), while it shouldn't.
Trails
I tried to implement my own CacheKeyGenerator, that will take into account the type of the calling DomainDao:
applicationContext.xml
<ehcache:annotation-driven cache-manager="ehCacheManager" default-cache-key-generator="daoCacheKeyGenerator" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
<bean id="daoCacheKeyGenerator" class="myapp.dao.support.DaoCacheKeyGenerator" />
DaoCacheKeyGenerator.java
public class DaoCacheKeyGenerator implements CacheKeyGenerator<DaoCacheKey> {
#Override
public DaoCacheKey generateKey(MethodInvocation methodInvocation) {
Class<?> clazz = methodInvocation.getThis().getClass().getInterfaces()[0];
Method method = methodInvocation.getMethod();
String methodName = method.getName();
Class<?>[] parameterClasses = method.getParameterTypes();
return new DaoCacheKey(clazz, methodName, parameterClasses);
}
#Override
public DaoCacheKey generateKey(Object... data) {
return null;
}
}
DaoCacheKey.java
public class DaoCacheKey implements Serializable {
private static final long serialVersionUID = 338466521373614710L;
private Class<?> clazz;
private String methodName;
private Class<?>[] parameterClasses;
public DaoCacheKey(Class<?> clazz, String methodName, Class<?>[] parameterClasses) {
this.clazz = clazz;
this.methodName = methodName;
this.parameterClasses = parameterClasses;
}
#Override
public boolean equals(Object obj) { // <-- breakpoint
if (obj instanceof DaoCacheKey) {
DaoCacheKey other = (DaoCacheKey) obj;
if (clazz.equals(other.clazz)) {
// if #TriggersRemove, reset any cache generated by a find* method of the same DomainDao
boolean removeCache = !methodName.startsWith("find") && other.methodName.startsWith("find");
// if #Cacheable, check if the result has been previously cached
boolean getOrCreateCache = methodName.equals(other.methodName) && Arrays.deepEquals(parameterClasses, other.parameterClasses);
return removeCache || getOrCreateCache;
}
}
return false;
}
#Override
public int hashCode() { // <-- breakpoint
return super.hashCode();
}
}
The problem with the above DaoCacheKey, is that the equals method get never called (the program never breaks at least), but the hashCode one does, so the algorithm can't get applied.
Question
Has anyone already managed such a cache? If yes how? Does my try is relevant? If yes, how to make the equals method called, instead of the hashCode one? By extending an existing CacheKeyGenerator? If yes, which one?
Here is the working solution I finally adopted. Just few precisions: my domains all implement the Persistable interface of Spring. Moreover, since I'm using reflection, I'm not sure the time saved by the caching process won't be a bit reduced...
applicationContext.xml
<ehcache:annotation-driven cache-manager="ehCacheManager" default-cache-key-generator="daoCacheKeyGenerator" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
<bean id="daoCacheKeyGenerator" class="myapp.dao.support.cache.DaoCacheKeyGenerator" />
DaoCacheKeyGenerator.java (using the gentyref library)
public class DaoCacheKeyGenerator implements CacheKeyGenerator<DaoCacheKey> {
#SuppressWarnings("unchecked")
#Override
public DaoCacheKey generateKey(MethodInvocation methodInvocation) {
Method method = methodInvocation.getMethod();
Class<? extends GenericDao<?, ?>> daoType = (Class<? extends GenericDao<?, ?>>) methodInvocation.getThis().getClass().getInterfaces()[0];
Class<? extends Persistable<?>> domainType = getDomainType(daoType);
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] parameters = methodInvocation.getArguments();
return new DaoCacheKey(domainType, methodName, parameterTypes, parameters);
}
#SuppressWarnings("unchecked")
private Class<? extends Persistable<?>> getDomainType(Class<?> daoType) {
Type baseDaoType = GenericTypeReflector.getExactSuperType(daoType, GenericDao.class);
ParameterizedType parameterizedBaseDaoType = (ParameterizedType) baseDaoType;
return (Class<? extends Persistable<?>>) parameterizedBaseDaoType.getActualTypeArguments()[0];
}
#Override
public DaoCacheKey generateKey(Object... data) {
return null;
}
}
DaoCacheKey.java
public class DaoCacheKey implements Serializable {
private static final long serialVersionUID = 338466521373614710L;
private Class<? extends Persistable<?>> domainType;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] parameters;
public DaoCacheKey(Class<? extends Persistable<?>> domainType, String methodName, Class<?>[] parameterTypes, Object[] parameters) {
this.domainType = domainType;
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.parameters = parameters;
}
public Class<? extends Persistable<?>> getDomainType() {
return domainType;
}
#Override
public boolean equals(Object obj) {
return this == obj || obj instanceof DaoCacheKey && hashCode() == obj.hashCode();
}
#Override
public int hashCode() {
return Arrays.hashCode(new Object[] { domainType, methodName, Arrays.asList(parameterTypes), Arrays.asList(parameters) });
}
}
ehcache.xml
<cache name="dao"
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
timeToIdleSeconds="86400"
timeToLiveSeconds="86400"
memoryStoreEvictionPolicy="LFU">
<cacheEventListenerFactory class="myapp.dao.support.cache.DaoCacheEventListenerFactory" />
</cache>
DaoCacheEventListenerFactory.java
public class DaoCacheEventListenerFactory extends CacheEventListenerFactory {
#Override
public CacheEventListener createCacheEventListener(Properties properties) {
return new DaoCacheEventListener();
}
}
DaoCacheEventListener.java
public class DaoCacheEventListener implements CacheEventListener {
#SuppressWarnings("unchecked")
#Override
public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
DaoCacheKey daoCachekey = (DaoCacheKey) element.getKey();
List<Class<? extends Persistable<?>>> impacts = getOneToManyImpacts(daoCachekey.getDomainType());
for (DaoCacheKey daoCachedkey : (List<DaoCacheKey>) cache.getKeys()) {
if (impacts.contains(daoCachedkey.getDomainType())) {
cache.remove(daoCachedkey);
}
}
}
#SuppressWarnings("unchecked")
private List<Class<? extends Persistable<?>>> getOneToManyImpacts(Class<? extends Persistable<?>> domainType) {
List<Class<? extends Persistable<?>>> impacts = new ArrayList<Class<? extends Persistable<?>>>();
impacts.add(domainType);
for (Method method : domainType.getDeclaredMethods()) {
if (method.isAnnotationPresent(OneToMany.class)) {
ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType();
Class<? extends Persistable<?>> impactedDomainType = (Class<? extends Persistable<?>>) parameterizedType.getActualTypeArguments()[0];
if (!impacts.contains(impactedDomainType)) {
impacts.addAll(getOneToManyImpacts(impactedDomainType));
}
}
}
return impacts;
}
#Override
public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
}
#Override
public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
}
#Override
public void notifyElementExpired(Ehcache cache, Element element) {
}
#Override
public void notifyElementEvicted(Ehcache cache, Element element) {
}
#Override
public void notifyRemoveAll(Ehcache cache) {
}
#Override
public void dispose() {
}
#Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Hope that could help ;)
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);
}
}
I have following class, I need to get type in constructor, how can I do that?
public abstract class MyClass<T> {
public MyClass()
{
// I need T type here ...
}
}
EDIT:
Here is concrete example what I want to achieve:
public abstract class Dao<T> {
public void save(GoogleAppEngineEntity entity)
{
// save entity to datastore here
}
public GoogleAppEngineEntity getEntityById(Long id)
{
// return entity of class T, how can I do that ??
}
}
What I want to do is to have this class extended to all other DAOs, because other DAOs have some queries that are specific to those daos and cannot be general, but these simple queries should be generally available to all DAO interfaces/implementations...
You can get it, to some degree... not sure if this is useful:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
abstract class MyClass<T> {
public MyClass() {
Type genericSuperclass = this.getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericSuperclass;
Type type = pt.getActualTypeArguments()[0];
System.out.println(type); // prints class java.lang.String for FooClass
}
}
}
public class FooClass extends MyClass<String> {
public FooClass() {
super();
}
public static void main(String[] args) {
new FooClass();
}
}
We've done this
public abstract BaseClass<T>{
protected Class<? extends T> clazz;
public BaseClass(Class<? extends T> theClass)
{
this.clazz = theClass;
}
...
}
And in the subclasses,
public class SubClass extends BaseClass<Foo>{
public SubClass(){
super(Foo.class);
}
}
And you cannot simply add a constructor parameter?
public abstract class MyClass<T> {
public MyClass(Class<T> type) {
// do something with type?
}
}
If I'm not reading this wrong, wouldn't you just want
public <T> void save(T entity)
and
public <T> T getEntityById(Long id)
for your method signatures?