No console aparece:
org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
Ele funciona, salva apaga, lista, deleta, busca, mas o createCriteria aparece deprecated com o risco.
meu genericDAO completo:
package com.mmotta.drogaria2.dao;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import javax.persistence.criteria.CriteriaQuery;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import com.mmotta.drogaria2.util.HibernateUtil;
public class GenericDAOnew<Entidade> {
private Class<Entidade> classe;
@SuppressWarnings("unchecked")
public GenericDAOnew() {
// APIreflection, usado para fazer os métodos listar genéricos
this.classe = (Class<Entidade>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public void salvar(Entidade entidade) {
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
Transaction transacao = null;
try {
transacao = sessao.beginTransaction();
sessao.save(entidade);
transacao.commit(); //confirmando transacao
} catch (RuntimeException e) {
if(transacao != null) {
transacao.rollback(); //
}
throw e;
}finally {
sessao.close();
}
}
@SuppressWarnings("unchecked")
public List<Entidade> listar(){
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
try {
Criteria consulta = sessao.createCriteria(classe);
List<Entidade> resultado = consulta.list();
return resultado;
} catch (RuntimeException e) {
throw e;
}finally {
sessao.close();
}
}
@SuppressWarnings("unchecked")
public Entidade buscar(Long codigo){
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
try {
Criteria consulta = sessao.createCriteria(classe);
// adicionando restricao como o where do sql
consulta.add(Restrictions.idEq(codigo));
Entidade resultado = (Entidade) consulta.uniqueResult();
return resultado;
} catch (RuntimeException e) {
throw e;
}finally {
sessao.close();
}
}
public void excluir(Entidade entidade) {
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
Transaction transacao = null;
try {
transacao = sessao.beginTransaction();
sessao.delete(entidade);
transacao.commit(); //confirmando transacao
} catch (RuntimeException e) {
if(transacao != null) {
transacao.rollback(); //
}
throw e;
}finally {
sessao.close();
}
}
public void editar(Entidade entidade) {
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
Transaction transacao = null;
try {
transacao = sessao.beginTransaction();
sessao.update(entidade);
transacao.commit(); //confirmando transacao
} catch (RuntimeException e) {
if(transacao != null) {
transacao.rollback(); //
}
throw e;
}finally {
sessao.close();
}
}
}
Mas recomendo migrar pra JdbcTemplate que é mais leve e sem essas confusões de linguagem intermediária OO pra queries. Se ainda assim quiser algo pra JPA/Hibernate, o menos pior é o Spring Data:
2 curtidas
pior que é verdade e os comandos mudam muito a cada versão
Sempre achei Criteria uma solução extremamente bizarra. Prefiro escrever SQL diretamente sem modelo OO, mas pra quem gosta de queries em cima de modelo OO, embora seja engessado, HQL/JPQL é mais legível por ser mais próximo a SQL.
1 curtida
Tentei mudar o listar()
no GenericDAO
@SuppressWarnings(“unchecked”)
public List listar(){
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
try {
CriteriaBuilder builder = sessao.getCriteriaBuilder();
List<Entidade> criteria = (List<Entidade>) builder.createQuery(classe);
return criteria;
} catch (RuntimeException e) {
throw e;
}finally {
sessao.close();
}
}
mas deu erro no JUnit:
@Test
public void listar() {
EstadoDAO estadoDAO = new EstadoDAO();
List<Estado> resultado = estadoDAO.listar();
System.out.println("Total de registros encontrados : " + resultado.size() + " estados ");
for (Estado estado : resultado) {
System.out.println(estado.getSigla() + " - " + estado.getNome() + " codigo : " + estado.getCodigo());
}
}
deu:
java.lang.ClassCastException: class org.hibernate.query.criteria.internal.CriteriaQueryImpl cannot be cast to class java.util.List (org.hibernate.query.criteria.internal.CriteriaQueryImpl is in unnamed module of loader ‘app’; java.util.List is in module java.base of loader ‘bootstrap’)
at com.mmotta.drogaria2.dao.GenericDAOnew.listar(GenericDAOnew.java:57)
at com.mmotta.drogaria2.dao.EstadoDAOtest.listar(EstadoDAOtest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
ne baseei neste:
Assim vai ter muito stress. Faz do zero sem usar Criteria ou deixa o código como sempre funcionou.
é que sigo um tutorial de 7 anos, ele funciona mas com o risco de deprecado
Consegui:
@SuppressWarnings(“unchecked”)
public List listar(){
// capturando sessao aberta
Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
try {
//Get Criteria Builder
CriteriaBuilder builder = sessao.getCriteriaBuilder();
//Create Criteria
CriteriaQuery<Entidade> criteria = builder.createQuery(classe);
Root<Entidade> entidadeRoot = criteria.from(classe);
criteria.select(entidadeRoot);
//Use criteria to query with session to fetch all contacts
List<Entidade> resultado = sessao.createQuery(criteria).getResultList();
//Close session
sessao.close();
return resultado;
} catch (RuntimeException e) {
throw e;
}finally {
sessao.close();
}
}
Se isso te incomoda tanto, anota sua classe com @SuppressWarnings("deprecation")
.
É um paliativo, mas eu resolvi com o código acima