EntityManager x HibernateUtil
Senhores, bom dia!
Estou a iniciar um projeto novo e gostaria de implementar um controle transacional eficiente. Pensei no controle transacional disponibilizado pelo SpringFramework.
Na arquitetura utilizada pela nossa empresa, há a utilização de um factory (HibernateUtil) onde são controladas todas as sessões e transações e não utilizáva-mos o Spring na arquitetura antiga.
A dúvida é:
Se eu utilizar o EntityManager, independente de qual fwk seja, eu não preciso mais controlar as sessões e transações pelo meu factory?
Mateus Venancio
Curtidas 0
Respostas
Davi Costa
28/10/2010
Vc pode continuar usando seu factory sim, e usar o Spring para injeção de dependências.
Uma ótima estratégia.
Att Davi
Uma ótima estratégia.
Att Davi
GOSTEI 0
Mateus Venancio
28/10/2010
HibernateUtil
DAO
Esses são meu Factory e Dao.. me dê um exemplo de como fazer isso
public class HibernateUtil {
/**
* Construtor no-arg Protegido para evitar a criação da classe
*/
protected HibernateUtil() {
super();
}
/* Constante de caminho do arquivo de configuração do Hibernate */
/* Threads que controlarão a sessão e a transação */
private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();
/* Variaveis do Hibernate */
private static final Configuration cfg = new AnnotationConfiguration();
private static SessionFactory sessionFactory;
private static synchronized void buildSessionFactory() throws Exception {
if (sessionFactory == null) {
try {
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
throw e;
}
}
}
/**
* Método que retorna a instancia da Sessão.
*
* @return Session
* @throws Exception
* @throws SessionFactoryException
*/
public static Session getCurrentSession() throws HibernateException {
Session session = threadSession.get();
try {
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
buildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory
.openSession() : null;
threadSession.set(session);
}
} catch (Exception e) {
e.printStackTrace();
throw new HibernateException(e);
}
return session;
}
/**
* Método que fecha a sessão do Hibernate.
*
* @throws SessionFactoryException
*/
public static void doCloseSession() throws HibernateException {
Session session = threadSession.get();
threadSession.set(null);
try {
if (session != null) {
session.close();
}
session = threadSession.get();
} catch (Exception e) {
throw new HibernateException(e);
}
}
/**
* Método que inicia a transação do Hibernate.
*
* @throws SessionFactoryException
*/
public static void doBeginTransaction() throws HibernateException {
Transaction tx = threadTransaction.get();
try {
if (tx == null) {
tx = getCurrentSession().beginTransaction();
threadTransaction.set(tx);
}
} catch (Exception e) {
throw new HibernateException(e);
}
}
/**
* Método que executa o rollback da transação.
*
* @throws SessionFactoryException
*/
public static void doRollback() throws HibernateException {
Transaction tx = threadTransaction.get();
try {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
tx.rollback();
threadTransaction.set(null);
}
} catch (Exception e) {
throw new HibernateException(e);
}
}
// LIMPANDO CACHE PRIMÁRIO DO HIBERNATE
// UTILIZADO PARA OPERACOES EM BATCH
public static void doFlush() {
try {
getCurrentSession().flush();
getCurrentSession().clear();
} catch (Exception e) {
throw new HibernateException(e);
}
}
/**
* Método que commita a transação.
*
* @throws SessionFactoryException
*/
public static void doCommit() throws HibernateException {
Transaction tx = threadTransaction.get();
try {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
tx.commit();
threadTransaction.set(null);
}
} catch (Exception e) {
doRollback();
throw new HibernateException(e);
}
}
public static Statistics getStatistics() {
return sessionFactory.getStatistics();
}
@SuppressWarnings("unchecked")
public static void clearHibernateCache() {
try {
SessionFactory sf = sessionFactory;
Map<Object, EntityPersister> classMetadata = sf
.getAllClassMetadata();
for (EntityPersister ep : classMetadata.values()) {
if (ep.hasCache()) {
try {
ep.getCache().clear();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
Map<Object, AbstractCollectionPersister> collMetadata = sf
.getAllCollectionMetadata();
for (AbstractCollectionPersister acp : collMetadata.values()) {
if (acp.hasCache()) {
try {
acp.getCache().clear();
} catch (CacheException e) {
e.printStackTrace();
}
}
}
return;
} catch (Exception e) {
// TODO: handle exception
}
}
}
public class DAO<T> extends HibernateUtil implements IDAO<T> {
public DAO<T> addParamsEq(String key, Object value) {
paramsEq.put(key, value);
return this;
}
public void save(Collection<T> ts) {
int x = 0;
doBeginTransaction();
try {
for (T t : ts) {
try {
getCurrentSession().saveOrUpdate(t);
} catch (NonUniqueObjectException e) {
getCurrentSession().merge(t);
}
if (x >= 10 && x % 10 == 0) {
doFlush();
}
x++;
}
doCommit();
doFlush();
} catch (Exception e) {
e.printStackTrace();
doRollback();
} finally {
clearHibernateCache();
}
}
public DAO<T> addParamsLike(String key, String value) {
paramsLike.put(key, value);
return this;
}
public DAO<T> clearParamsEq() {
paramsEq.clear();
return this;
}
public IDAO<T> clearAllParams() {
paramsEq.clear();
paramsLike.clear();
paramsIsNotNull.clear();
paramsIsNull.clear();
return this;
}
public DAO<T> clearParamsLike() {
paramsLike.clear();
return this;
}
public T getWithParams(Class<T> clas) {
Criteria query = getCurrentSession().createCriteria(clas);
query.setCacheable(true);
for (String field : paramsEq.keySet())
query.add(Restrictions.eq(field, paramsEq.get(field)));
for (String field : paramsLike.keySet())
query.add(Restrictions.like(field, paramsLike.get(field), MatchMode.ANYWHERE));
return (T)query.uniqueResult();
}
public T getEvictingCache(Class<T> clas, Integer id) {
doBeginTransaction();
T t = (T) getCurrentSession().load(clas, id);
getCurrentSession().evict(t);
doCommit();
return t;
}
public T getEvictingCache(Class<T> clas, String campo, Object valor) {
T t = (T) getCurrentSession().createCriteria(clas).add(
Restrictions.eq(campo, valor)).uniqueResult();
getCurrentSession().evict(t);
return t;
}
public T get(Class<T> clas, Integer id) {
doBeginTransaction();
T t = (T) getCurrentSession().load(clas, id);
doCommit();
return t;
}
public List<T> list(Class<T> clas) {
return getCurrentSession().createCriteria(clas).list();
}
public void save(T t) throws ConstraintViolationException,UnsatisfiedDependencyException, Exception {
try {
if(!getCurrentSession().getTransaction().isActive()){
throw new UnsatisfiedDependencyException("INICIALIZE UMA TRANSAÇÃO");
}
getCurrentSession().saveOrUpdate(t);
} catch (NonUniqueObjectException e) {
getCurrentSession().merge(t);
} catch (ConstraintViolationException e) {
throw e;
} catch (Exception e) {
throw e;
}
}
public T get(Class<T> clas, String campo, Object valor) {
return (T) getCurrentSession().createCriteria(clas).add(
Restrictions.eq(campo, valor)).uniqueResult();
}
public List<T> search(Class<T> clas, String orderField) {
return searchWithCache(clas, null, orderField);
}
public List<T> searchWithCache(Class<T> clas, CacheMode cacheMode,
String orderField) {
try {
Criteria query = getCurrentSession().createCriteria(clas);
if (cacheMode != null) {
query.setCacheable(true);
query.setCacheMode(cacheMode);
} else {
query.setCacheable(false);
}
System.out.println("[ParamsEQ] "+paramsEq);
for (String key : paramsEq.keySet())
query.add(Restrictions.eq(key, paramsEq.get(key)));
for (String key : paramsLike.keySet())
query.add(Restrictions.like(key, paramsLike.get(key),
MatchMode.ANYWHERE));
for(String fieldNull : paramsIsNull)
query.add(Restrictions.isNull(fieldNull));
for(String fieldNotNull : paramsIsNotNull)
query.add(Restrictions.isNotNull(fieldNotNull));
query.addOrder(Order.asc(orderField));
// query.setMaxResults(1000) ;
List<T> returnn = query.list();
return returnn;
} finally {
clearAllParams();
}
}
public IDAO<T> clearParamsIsNotNull() {
paramsIsNull.clear();
return this;
}
public IDAO<T> clearParamsIsNull() {
paramsIsNotNull.clear();
return this;
}
public IDAO<T> addParamsNotNull(String field) {
paramsIsNotNull.add(field);
return this;
}
public IDAO<T> addParamsNull(String field) {
paramsIsNull.add(field);
return this;
}
}
GOSTEI 0
Davi Costa
28/10/2010
Assim vc vai injetar seus serviços, onde for usá-los. E também injetar seus daos nos seus serviços.
Como também pode injetar seus serviços nos seus controllers. Diminuindo acoplamento
O exemplo é complicado de passar. Precisaria de bem mais informações, por exemplo versão do Spring.
Agora se vc pesquisar a versão que vc está usando no site do Spring facilmente vai ver algum exemplo.
Ou até mesmo no google.
Att Davi
Como também pode injetar seus serviços nos seus controllers. Diminuindo acoplamento
O exemplo é complicado de passar. Precisaria de bem mais informações, por exemplo versão do Spring.
Agora se vc pesquisar a versão que vc está usando no site do Spring facilmente vai ver algum exemplo.
Ou até mesmo no google.
Att Davi
GOSTEI 0
Mateus Venancio
28/10/2010
Davi, a injeção eu faço normalmente..
O Exemplo que solicitei era de Como utilizar o EntityManager no meu dao...
@Service
@SuppressWarnings("unchecked")
public class EmpresaBusiness implements IEmpresaBusiness {
@Autowired
private IDAO dao;
public void setDao(IDAO dao) {
this.dao = dao;
}
}
GOSTEI 0
Davi Costa
28/10/2010
Cra vai ter várias formas de vc fazer, uma delas é usar a anotação:
@PersistenceContext
protected EntityManager entityManager;
e depois usá-lo normalmente:
entityManager.persist(obj);
Mas existem outras formas de instanciar o EntityManager.
Att Davi
@PersistenceContext
protected EntityManager entityManager;
e depois usá-lo normalmente:
entityManager.persist(obj);
Mas existem outras formas de instanciar o EntityManager.
Att Davi
GOSTEI 0
Dyego Carmo
28/10/2010
Opa !
Conseguiu resolver colega ?
ValeuZ !
Conseguiu resolver colega ?
ValeuZ !
GOSTEI 0