How to implement GenericDAO class on Hibernate - java

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 {
}

Related

how to implement generic spring jpa repository for all entities

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

Inheritence using java generics not working as expected

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?

error in spring hibernate integration

everytime when i am running my spring with hibernate socket program it saves for the first time but i am sending infinitely from the client side but in server end only first time it is saving..What type of problem i am facing?? how to resolve
package utilclass;
import org.hibernate.*;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class HibernateUtemplate {
private static HibernateTemplate template;
public void setTemplate(HibernateTemplate template){
HibernateUtemplate.template=template;
}
public static SessionFactory getSessionFactory(){
return template.getSessionFactory();
}
public static Session getSession(){
getSessionFactory().getCurrentSession().beginTransaction();
return getSessionFactory().getCurrentSession();
}
public static void commitTransaction() {
getSession().getTransaction().commit();
}
public static void rollbackTransaction() {
getSession().getTransaction().rollback();
}
public static void closeSession() {
getSession().close();
}
}
this is my generic file
package daoimplclasses;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import utilclass.HibernateUtemplate;
import daointerfaces.GenericDao;
public abstract class GenericDaoimpl<T, ID extends Serializable> implements GenericDao<T, ID> {
//HibernateTemplate template;
protected Session getSession() {
return HibernateUtemplate.getSession();
}
public void save(T entity) {
//template.saveOrUpdate(entity);
HibernateUtemplate.getSession().saveOrUpdate(entity);
// HibernateUtemplate.beginTransaction().saveOrUpdate(entity);
}
public void merge(T entity) {
// template.merge(entity);
HibernateUtemplate.getSession().merge(entity);
// HibernateUtemplate.beginTransaction().merge(entity);
}
public void update(T entity) {
// template.update(entity);
HibernateUtemplate.getSession().update(entity);
// HibernateUtemplate.beginTransaction().update(entity);
}
public void delete(T entity) {
// template.delete(entity);
HibernateUtemplate.getSession().delete(entity);
//HibernateUtemplate.beginTransaction().delete(entity);
}
public List<T> findMany(Query query) {
List<T> t;
t = (List<T>) query.list();
return t;
}
public T findOne(Query query) {
T t;
t = (T) query.uniqueResult();
return t;
}
public T findByID(Class claz,String siteid){
T t=null;
//t=(T)template.get(claz, siteid);
t=(T) HibernateUtemplate.getSession().get(claz, siteid);
//t=(T) HibernateUtemplate.beginTransaction().get(claz, siteid);
return t;
}
public List<T> findAll(Class clazz) {
List<T> T = null;
Query query= HibernateUtemplate.getSession().createQuery("from "+clazz.getName());
// Query query= HibernateUtemplate.beginTransaction().createQuery("from "+clazz.getName());
T = query.list();
return T;
}
}

Java - Singleton is causing null errors

I made a DAO class with factory method and the specific DAO returns singleton, a single instance of the DAO. But I been tracing it and its being created but I try to call on it and it always null.
Just to explain the storage factory
I call on DAOFactory to get RAMDAOFactory to get to RAMUserDAO
If there is better way to handle RAM, Serialization and SQL type DAOs or CRUD please let me know.
class that I'm calling the storage from.
public class Registration
{
private UserDAO userStorage;
private static Logger log = LogClass.getLog();
Registration(DAOFactoryType typeDataStorage)
{
userStorage = DAOFactory.getDAOFactory(typeDataStorage).getUserDAO();
log.trace("insdie Reg");
}
void addUser(String userName, String password, UserType... args)
throws Exception
{
List<UserType> userTypes = new ArrayList<UserType>(args.length);
for (UserType userType : args)
{
log.trace("userType " + userType);
userTypes.add(userType);
}
User newUser = new DefaultUser(userName, password, userTypes);
log.trace("newUser " + newUser);
if (userStorage != null)
{
userStorage.insert(newUser);
}
else
{
log.trace("userStorage null");
}
}
}
This is my DAOFactory
public abstract class DAOFactory
{
private static Logger log = LogClass.getLog();
public abstract TradeDAO getTradeDAO();
public abstract UserDAO getUserDAO();
public abstract LogDAO getLogDAO();
public static DAOFactory getDAOFactory(DAOFactoryType factoryType)
{
switch (factoryType)
{
case SQL:
return new SQLDAOFactory();
case RAM:
log.trace("insdie RAM");
return new RAMDAOFactory();
case SERIAL:
return new SerialDAOFactory();
default:
return null;
}
}
}
RAMDAOFactory
public class RAMDAOFactory extends DAOFactory
{
private static Logger log = LogClass.getLog();
private TradeDAO ramTradeDAO;
private UserDAO ramUserDAO;
private LogDAO ramLogDAO;
public RAMDAOFactory()
{
log.trace("insdie RAMDAOFactory");
RAMUserDAO.getRAMUserDAO();
RAMTradeDAO.getRAMTradeDAO();
RAMLogDAO.getRAMLogDAO();
}
#Override
public TradeDAO getTradeDAO()
{
return ramTradeDAO;
}
#Override
public UserDAO getUserDAO()
{
return ramUserDAO;
}
#Override
public LogDAO getLogDAO()
{
return ramLogDAO;
}
}
This is my UserDAO
public class RAMUserDAO implements UserDAO
{
/*
* Map<Integer, List<byte[]>> userHash; List<byte[]> arrayHashSalt;
*/
private static RAMUserDAO userDAO = null;
private Map<String, User> userList;
private static Logger log = LogClass.getLog();
private RAMUserDAO()
{
userList = new HashMap<String, User>();
log.trace("insdie RAMUserDAO constructor");
}
public static RAMUserDAO getRAMUserDAO()
{
log.trace("insdie getRAMUserDAO");
if(userDAO == null) {
log.trace("insdie new RAMUserDAO()");
userDAO = new RAMUserDAO();
}
/*if (userDAO == null)
{
synchronized (RAMUserDAO.class)
{
if (userDAO == null)
{
userDAO = new RAMUserDAO();
}
}
}*/
return userDAO;
}
#Override
public void insert(User user) throws Exception
{
log.trace("insdie insert");
userList.put(user.getUserName(), user);
}
}
The oversight was in RAMDAOFactory and fix was:
public class RAMDAOFactory extends DAOFactory
{
private static Logger log = LogClass.getLog();
#Override
public TradeDAO getTradeDAO()
{
return RAMTradeDAO.getRAMTradeDAO();
}
#Override
public UserDAO getUserDAO()
{
return RAMUserDAO.getRAMUserDAO();
}
#Override
public LogDAO getLogDAO()
{
return RAMLogDAO.getRAMLogDAO();
}
}
You've called the methods
public RAMDAOFactory()
{
log.trace("insdie RAMDAOFactory");
RAMUserDAO.getRAMUserDAO();
RAMTradeDAO.getRAMTradeDAO();
RAMLogDAO.getRAMLogDAO();
}
but you haven't assigned their value to anything
#Override
public UserDAO getUserDAO()
{
return ramUserDAO;
}
Either always call
RAMUserDao.getRAMUserDAO();
when you want to return the UserDAO or assign it to ramUserDAO and return that.

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