Olá a todos,
estou com um problema que não consigo resolver, veja os códigos abaixo:
/**
* HibernateUtil.java
*
* $Id$
*
*/
package util;
import cliente.Cliente;
import endereco.Endereco;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import produto.Produto;
public class HibernateUtil {
private static final long serialVersionUID = 1L;
private static HibernateUtil me;
private SessionFactory sessionFactory;
private HibernateUtil(){
sessionFactory = new AnnotationConfiguration()
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect")
.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/vendas")
.setProperty("hibernate.connection.username", "root")
.setProperty("hibernate.connection.password", "comecome")
.setProperty("hibernate.hbm2ddl.auto", "update")
.setProperty("hibernate.show_sql", "true")
.setProperty("hibernate.format_sql", "true")
.setProperty("hibernate.c3p0.acquire_increment", "1")
.setProperty("hibernate.c3p0.idle_test_period", "100")
.setProperty("hibernate.c3p0.max_size", "10")
.setProperty("hibernate.c3p0.max_statements", "0")
.setProperty("hibernate.c3p0.min_size", "5")
.setProperty("hibernate.c3p0.timeout", "600")
.addAnnotatedClass(Produto.class)
.addAnnotatedClass(Cliente.class)
.addAnnotatedClass(Endereco.class)
.buildSessionFactory();
}
public Session getSession() {
Session toReturn = sessionFactory.openSession();
//toReturn.beginTransaction();
return toReturn;
}
public static HibernateUtil getInstance() {
if (me== null){
me = new HibernateUtil();
}
return me;
}
}
GenericDAO
package util;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public abstract class GenericDAO {
public GenericDAO(){
}
protected Session getSession() {
return DAO.getSession();
// return HibernateUtil.getInstance().getSession();
}
protected void savePojo(Serializable pojo) {
Session ses = getSession();
ses.save(pojo);
//ses.save(pojo);
// ses.getTransaction().commit();
// ses.close();
}
protected void saveorUpdatePojo(Serializable pojo) {
Session ses = getSession();
ses.saveOrUpdate(pojo);
//ses.getTransaction().commit();
//ses.close();
}
protected void updatePojo(Serializable pojo) {
Session ses = getSession();
ses.saveOrUpdate(pojo);
// ses.getTransaction().commit();
// ses.close();
}
protected Serializable mergePojo(Serializable pojo) {
Session ses = getSession();
Object toReturn = ses.merge(pojo);
// ses.getTransaction().commit();
//ses.close();
return (Serializable) toReturn;
}
protected <T extends Serializable> T getPojo(Class<T> classToSearch,Serializable key) {
Session ses = getSession();
Serializable toReturn = (Serializable) ses.get(classToSearch, key);
//ses.getTransaction().commit();
//ses.close();
return (T) toReturn;
}
protected void removePojo(Serializable pojoToRemote) {
Session ses = getSession();
ses.delete(pojoToRemote);
//ses.getTransaction().commit();
// ses.close();
}
protected Serializable getPurePojo(String query,Object... params) {
Session ses = getSession();
Query qr = ses.createQuery(query);
for (int i = 0; i < params.length; i+=2) {
qr.setString(params[i].toString(), params[i+1].toString());
}
Object toReturn = qr.uniqueResult();
// ses.getTransaction().commit();
// ses.close();
return (Serializable) toReturn;
}
protected <T extends Serializable> List<T> getPureList(Class<T> classToCast,String query,Object... params) {
Session ses = getSession();
Query qr = ses.createQuery(query);
for (int i = 0; i < params.length; i+=2) {
qr.setString(params[i].toString(), params[i+1].toString());
//qr.setParameter(i, params[i-1]);
}
@SuppressWarnings("unchecked")
List<T> toReturn = qr.list();
//ses.getTransaction().commit();
//ses.close();
return toReturn;
}
}
DAO
package util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DAO {
private static ThreadLocal threadlocal = new ThreadLocal();
private static SessionFactory sessionFactory = new Configuration().configure().
buildSessionFactory();
//private static SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
public DAO() {
// TODO Auto-generated constructor stub
}
public static Session getSession() {
Session session = (Session) threadlocal.get();
if (session == null) {
session = sessionFactory.openSession();
threadlocal.set(session);
System.out.println("Thread local");
}
return session;
}
public void begin() {
getSession().beginTransaction();
}
public void commit() {
getSession().getTransaction().commit();
}
public void rollback() {
getSession().getTransaction().rollback();
}
public void close() {
getSession().close();
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
//passamos ele para o Filter
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory) {
DAO.sessionFactory = sessionFactory;
}
}
Filtro
package util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
public class HibernateSessionRequestFilter implements Filter {
private static Log log = LogFactory.getLog(HibernateSessionRequestFilter.class);
private SessionFactory sf;
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
try {
log.debug("Starting a database transaction");
sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// Commit and cleanup
log.debug("Committing the database transaction");
sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
log.error("This interceptor does not implement optimistic concurrency control!");
log.error("Your application will not work until you add compensation actions!");
// Rollback, close everything, possibly compensate for any permanent changes
// during the conversation, and finally restart business conversation. Maybe
// give the user of the application a chance to merge some of his work with
// fresh data... what you do here depends on your applications design.
throw staleEx;
} catch (Throwable ex) {
// Rollback only
ex.printStackTrace();
try {
if (sf.getCurrentSession().getTransaction().isActive()) {
log.debug("Trying to rollback database transaction after exception");
sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
// Let others handle it... maybe another interceptor for exceptions?
throw new ServletException(ex);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
log.debug("Obtaining SessionFactory from static HibernateUtil singleton");
sf = DAO.getSessionFactory();
// sf = HibernateUtil.getInstance().getSessionFactory();
System.out.println("Iniciou filtro");
}
@Override
public void destroy() {}
}
ProductDAO
package Dao;
import java.io.Serializable;
import java.util.List;
import produto.Produto;
import util.GenericDAO;
/**
*
* @author wellington
*/
public class ProductDAO extends GenericDAO implements Serializable {
public ProductDAO() {
}
public void saveProduto(Produto produto) {
savePojo(produto);
}
public void saveOrUpdateProduto(Produto produto) {
saveorUpdatePojo(produto);
}
public void removeProduto(Produto produto) {
removePojo(produto);
}
public void updateProduto(Produto produto) {
updatePojo(produto);
}
public Produto getProduto(int idProduto) {
Produto produto = getPojo(Produto.class, idProduto);
return produto;
}
public List<Produto> getProdutos() {
return getPureList(Produto.class, "from Produto");
}
public Produto mergeProduto(Produto produto) {
return (Produto) mergePojo(produto);
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/vendas</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">comecome</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping class="cliente.Cliente"/>
<mapping class="produto.Produto"/>
<mapping class="venda.Venda"/>
<mapping class="endereco.Endereco"/>
</session-factory>
</hibernate-configuration>
ProdutoController
package controller;
import Dao.ProductDAO;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import produto.Produto;
@ManagedBean
@SessionScoped
public class ProdutoController implements Serializable{
private Produto produtoSelected = new Produto();
private List<Produto> cachedProduto = null;
// private ProdutoDao produtoDao = new ProdutoDao();
private ProductDAO productDAO = new ProductDAO();
public ProdutoController() {
}
public Produto getProdutoSelected() {
return produtoSelected;
}
public void setProdutoSelected(Produto produtoSelected) {
this.produtoSelected = produtoSelected;
}
public List<Produto> getCachedProduto() {
if (cachedProduto == null) {
cachedProduto = productDAO.getProdutos();
}
return cachedProduto;
}
public String prepareAddrProduto(){
this.produtoSelected = new Produto();
return "salvar";
}
public String finishAddProduto(){
//produtoDao.salvar(produtoSelected);
productDAO.saveProduto(produtoSelected);
this.cachedProduto = null;
return "index";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<filter>
<filter-name>HibernateFiltro</filter-name>
<filter-class>util.HibernateSessionRequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFiltro</filter-name>
<url-pattern>*.faces</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.faces</welcome-file>
</welcome-file-list>
</web-app>
index.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="pt-br"/>
<title lang="pt-br">GCM Itabirito</title>
<style type="text/css" lang="pt-br">
body {background-color: #1E90FF}
</style>
</h:head>
<h:body>
<f:view>
<h:form>
<h1><h:outputText value="List"/></h1>
<h:dataTable value="#{produtoController.cachedProduto}" var="item">
<h:column>
<f:facet name="header">
<h:outputText value="Id"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Unidade"/>
</f:facet>
<h:outputText value="#{item.unidade}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Descricao"/>
</f:facet>
<h:outputText value="#{item.descricao}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="DataCadastro"/>
</f:facet>
<h:outputText value="#{item.dataCadastro}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Estoque"/>
</f:facet>
<h:outputText value="#{item.estoque}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Valor"/>
</f:facet>
<h:outputText value="#{item.valor}"/>
</h:column>
</h:dataTable>
<h:commandButton value="Novo" action="#{produtoController.prepareAddrProduto()}"/><br/>
</h:form>
<br/>
</f:view>
</h:body>
</html>
salvar.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>TODO supply a title</title>
</h:head>
<h:body>
<h:form>
<h1><h:outputText value="Create/Edit"/></h1>
<h:panelGrid columns="2">
<h:outputLabel value="Unidade:" for="unidade" />
<h:inputText id="unidade" value="#{produtoController.produtoSelected.unidade}" title="Unidade" />
<h:outputLabel value="Descricao:" for="descricao" />
<h:inputText id="descricao" value="#{produtoController.produtoSelected.descricao}" title="Descricao" />
<h:outputLabel value="DataCadastro:" for="dataCadastro" />
<h:inputText id="dataCadastro" value="#{produtoController.produtoSelected.dataCadastro}" title="DataCadastro" >
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:inputText>
<h:outputLabel value="Estoque:" for="estoque" />
<h:inputText id="estoque" value="#{produtoController.produtoSelected.estoque}" title="Estoque" />
<h:outputLabel value="Valor:" for="valor" />
<h:inputText id="valor" value="#{produtoController.produtoSelected.valor}" title="Valor" />
</h:panelGrid>
<h:commandButton value="Salvar" action="#{produtoController.finishAddProduto()}"/><br/>
</h:form>
</h:body>
</html>
Quando inicio o index.xhtml ele exibe os dados contidos no banco.
Quando clico em Novo na página index.xhtml redireciono para a página salvar.xhtml.
Então preencho os campos e clico em salvar e sou redirecionado para index.xhtml novamente.
Veja a saída no console:
Iniciou filtro
00:39:41,619 INFO [http-apr-8080-exec-8] ConnectionProviderInitiator:188 - HHH000130: Instantiating explicit connection provider: org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider
00:39:41,620 INFO [http-apr-8080-exec-8] C3P0ConnectionProvider:128 - HHH010002: C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/vendas
00:39:41,620 INFO [http-apr-8080-exec-8] C3P0ConnectionProvider:129 - HHH000046: Connection properties: {user=root, password=****}
00:39:41,621 INFO [http-apr-8080-exec-8] C3P0ConnectionProvider:132 - HHH000006: Autocommit mode: false
00:39:41,635 INFO [http-apr-8080-exec-8] MLog:80 - MLog clients using log4j logging.
00:39:41,728 INFO [http-apr-8080-exec-8] C3P0Registry:204 - Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
00:39:41,852 INFO [http-apr-8080-exec-8] AbstractPoolBackedDataSource:462 - Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@539870a6 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@1d87a05b [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> z8kfsx8t1b5dq7cmfx7xl|e3b7a5, idleConnectionTestPeriod -> 100, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 600, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@ff77e0a6 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> z8kfsx8t1b5dq7cmfx7xl|1e31239, jdbcUrl -> jdbc:mysql://localhost:3306/vendas, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> z8kfsx8t1b5dq7cmfx7xl|12fdbbe, numHelperThreads -> 3 ]
00:39:41,950 INFO [http-apr-8080-exec-8] Dialect:123 - HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
00:39:41,951 INFO [http-apr-8080-exec-8] LobCreatorBuilder:120 - HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
00:39:41,953 INFO [http-apr-8080-exec-8] TransactionFactoryInitiator:68 - HHH000399: Using default transaction strategy (direct JDBC transactions)
00:39:41,953 INFO [http-apr-8080-exec-8] ASTQueryTranslatorFactory:48 - HHH000397: Using ASTQueryTranslatorFactory
00:39:41,984 INFO [http-apr-8080-exec-8] SchemaUpdate:182 - HHH000228: Running hbm2ddl schema update
00:39:41,985 INFO [http-apr-8080-exec-8] SchemaUpdate:193 - HHH000102: Fetching database metadata
00:39:41,990 INFO [http-apr-8080-exec-8] SchemaUpdate:205 - HHH000396: Updating schema
00:39:41,998 INFO [http-apr-8080-exec-8] TableMetadata:65 - HHH000261: Table found: vendas.cliente
00:39:41,999 INFO [http-apr-8080-exec-8] TableMetadata:66 - HHH000037: Columns: [telefone_residencial, estado_civil, telefone_empresarial, nomde_pai, orgao_emissor, sexo, data_nascimento, rg, id_endereco, telefone_celular, renda, id, email, nome_mae, natural_cidade, natural_estado, cpf, nome, data_cadastro, estado_emissor]
00:39:41,999 INFO [http-apr-8080-exec-8] TableMetadata:68 - HHH000108: Foreign keys: [fk334b85fab00422db]
00:39:41,999 INFO [http-apr-8080-exec-8] TableMetadata:69 - HHH000126: Indexes: [primary, fk334b85fab00422db]
00:39:42,004 INFO [http-apr-8080-exec-8] TableMetadata:65 - HHH000261: Table found: vendas.endereco
00:39:42,004 INFO [http-apr-8080-exec-8] TableMetadata:66 - HHH000037: Columns: [id, cidade, bairro, estado, complemento, endereco, numero]
00:39:42,004 INFO [http-apr-8080-exec-8] TableMetadata:68 - HHH000108: Foreign keys: []
00:39:42,004 INFO [http-apr-8080-exec-8] TableMetadata:69 - HHH000126: Indexes: [primary]
00:39:42,009 INFO [http-apr-8080-exec-8] TableMetadata:65 - HHH000261: Table found: vendas.produto
00:39:42,009 INFO [http-apr-8080-exec-8] TableMetadata:66 - HHH000037: Columns: [id, valor, estoque, data_cadastro, descricao, unidade]
00:39:42,010 INFO [http-apr-8080-exec-8] TableMetadata:68 - HHH000108: Foreign keys: []
00:39:42,010 INFO [http-apr-8080-exec-8] TableMetadata:69 - HHH000126: Indexes: [primary]
00:39:42,010 INFO [http-apr-8080-exec-8] SchemaUpdate:240 - HHH000232: Schema update complete
Hibernate:
select
produto0_.id as id8_,
produto0_.data_cadastro as data2_8_,
produto0_.descricao as descricao8_,
produto0_.estoque as estoque8_,
produto0_.unidade as unidade8_,
produto0_.valor as valor8_
from
produto produto0_
Hibernate:
insert
into
produto
(data_cadastro, descricao, estoque, unidade, valor)
values
(?, ?, ?, ?, ?)
Hibernate:
select
produto0_.id as id8_,
produto0_.data_cadastro as data2_8_,
produto0_.descricao as descricao8_,
produto0_.estoque as estoque8_,
produto0_.unidade as unidade8_,
produto0_.valor as valor8_
from
produto produto0_
Porém, quando vou no banco de dados mysql o produto não foi inserido.
Já procurei a solução no google, aqui no guj e nada.
Por favor, alguém pode me ajudar?
Muito obrigado desde já.
