Results 1 to 12 of 12
  1. #1
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Problem with hibernate insert

    Hi guys, i'm from Brasil and i apolgize for my English.

    I'm getting a really wierd "error""
    I'm doing a personal finances system, I made the user and account registration, and i made in a way that you can register your 1st account on the registration screen. When i create the account(Conta) with the user(Usuário) registration, everything seems to be just fine, i get de description(Descrição), the Initial Value(Saldo inicial), the date(Data) and the id from the user(cod_usuario). And on the DB everything is just fine.
    But, when i try to set a new Account from the accounts page, the description and the initial values don't appear, the account gets to the DB with the fields descrição(Description) and saldo inicial (initial value) as NULL and 0.0.
    But the Date, the id of the account, and the id of the user are correct.
    This is my DB information, if you notice it has 2 registers that are correct(made from the user screen, when registering), and the others one is from the account screen.
    How is that possible?
    des_conta == descricao

    Java Code:
    +-----------+-------------+------------+---------------------+---------------+----------+  
    | cod_conta | cod_usuario | des_conta | dat_cadastro | saldo_inicial | favorita |  
    +-----------+-------------+------------+---------------------+---------------+----------+  
    | 8            | 1                | Banco Itau | 2011-09-13 18:24:54 | 1000                 | |  
    | 12           | 1               | NULL         | 2011-09-13 21:56:32 | 0                     | |  
    | 13           | 1                | NULL        | 2011-09-13 21:57:15 | 0                     | |  
    | 14           | 2               | Banco HSBC | 2011-09-13 21:58:24 | 10000             | |  
    | 18           | 2               | NULL          | 2011-09-13 22:56:59 | 0                     | |  
    +-----------+-------------+------------+---------------------+---------------+----------+
    this is my query




    Classe Conta (account)

    Java Code:
    package financeiro.conta;
    
    import java.io.Serializable;
    import java.util.Date;
    
    import javax.persistence.Entity;
    import javax.persistence.*;
    import javax.persistence.Table;
    
    import org.hibernate.annotations.*;
    
    
    import financeiro.usuario.Usuario;
    
    @Entity
    @Table(name="conta_bancaria")
    public class Conta implements Serializable {
    
    
    
    	
    	private static final long serialVersionUID = 1L;
    
    	@Id
    	@GeneratedValue
    	@Column(name="cod_conta")
    	private Integer	conta;
    
    	@ManyToOne
    	@OnDelete(action=OnDeleteAction.CASCADE)
    	@JoinColumn(name = "cod_usuario", nullable = false)
    	private Usuario	usuario;
    
    	@Column(name="des_conta")
    	private String descricao;
    
    	@Column(name="dat_cadastro", nullable = false, updatable = false)
    	private Date dataCadastro;
    
    	@Column(name="saldo_inicial")
    	private float saldoInicial;
    
    	@Column(name="favorita")
    	private boolean	favorita;
    
    	public Integer getConta() {
    		return conta;
    	}
    
    	public void setConta(Integer conta) {
    		this.conta = conta;
    	}
    
    	public Usuario getUsuario() {
    		return usuario;
    	}
    
    	public void setUsuario(Usuario usuario) {
    		this.usuario = usuario;
    	}
    
    	public String getDescricao() {
    		return descricao;
    	}
    
    	public void setDescricao(String descricao) {
    		this.descricao = descricao;
    	}
    
    	public Date getDataCadastro() {
    		return dataCadastro;
    	}
    
    	public void setDataCadastro(Date dataCadastro) {
    		this.dataCadastro = dataCadastro;
    	}
    
    	public float getSaldoInicial() {
    		return saldoInicial;
    	}
    
    	public void setSaldoInicial(float saldoInicial) {
    		this.saldoInicial = saldoInicial;
    	}
    
    	public boolean isFavorita() {
    		return favorita;
    	}
    
    	public void setFavorita(boolean favorita) {
    		this.favorita = favorita;
    	}
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + ((conta == null) ? 0 : conta.hashCode());
    		result = prime * result + ((dataCadastro == null) ? 0 : dataCadastro.hashCode());
    		result = prime * result + ((descricao == null) ? 0 : descricao.hashCode());
    		result = prime * result + (favorita ? 1231 : 1237);
    		result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
    		result = prime * result + Float.floatToIntBits(saldoInicial);
    		return result;
    	}
    
    	@Override
    	public boolean equals(Object obj) {
    		if (this == obj)
    			return true;
    		if (obj == null)
    			return false;
    		if (getClass() != obj.getClass())
    			return false;
    		Conta other = (Conta) obj;
    		if (conta == null) {
    			if (other.conta != null)
    				return false;
    		} else if (!conta.equals(other.conta))
    			return false;
    		if (dataCadastro == null) {
    			if (other.dataCadastro != null)
    				return false;
    		} else if (!dataCadastro.equals(other.dataCadastro))
    			return false;
    		if (descricao == null) {
    			if (other.descricao != null)
    				return false;
    		} else if (!descricao.equals(other.descricao))
    			return false;
    		if (favorita != other.favorita)
    			return false;
    		if (usuario == null) {
    			if (other.usuario != null)
    				return false;
    		} else if (!usuario.equals(other.usuario))
    			return false;
    		if (Float.floatToIntBits(saldoInicial) != Float.floatToIntBits(other.saldoInicial))
    			return false;
    		return true;
    	}
    
    }
    Classe ContaDAO

    Java Code:
    package financeiro.conta;
    
    import java.util.List;
    
    import financeiro.usuario.Usuario;
    
    public interface ContaDAO {
    
    	public void salvar(Conta conta);
    
    	public void excluir(Conta conta);
    
    	public Conta carregar(Integer conta);
    
    	public List<Conta> listar(Usuario usuario);
    
    	public Conta buscarFavorita(Usuario usuario);
    }
    Classe ContaDAOHibernate
    Java Code:
    package financeiro.conta;
    
    import java.util.List;
    
    import org.hibernate.Criteria;
    import org.hibernate.Session;
    import org.hibernate.criterion.Restrictions;
    
    import financeiro.usuario.Usuario;
    
    public class ContaDAOHibernate implements ContaDAO {
    
    	private Session	session;
    
    	public void setSession(Session session) {
    		this.session = session;
    	}
    
    	@Override
    	public void excluir(Conta conta) {
    		this.session.delete(conta);
    	}
    
    	@Override
    	public void salvar(Conta conta) {
    		this.session.saveOrUpdate(conta);
    	}
    
    	@Override
    	public Conta carregar(Integer conta) {
    		return (Conta) this.session.get(Conta.class, conta);
    	}
    
    	@SuppressWarnings("unchecked")
    	@Override
    	public List<Conta> listar(Usuario usuario) {
    
    		Criteria criteria = this.session.createCriteria(Conta.class);
    		criteria.add(Restrictions.eq("usuario", usuario));
    
    		return criteria.list();
    	}
    
    	@Override
    	public Conta buscarFavorita(Usuario usuario) {
    
    		Criteria criteria = this.session.createCriteria(Conta.class);
    		criteria.add(Restrictions.eq("usuario", usuario));
    		criteria.add(Restrictions.eq("favorita", true));
    
    		return (Conta) criteria.uniqueResult();
    	}
    }
    Classe ContaRN

    Java Code:
    package financeiro.conta;
    
    import java.util.Date;
    import java.util.List;
    
    import financeiro.usuario.Usuario;
    import financeiro.util.DAOFactory;
    
    public class ContaRN {
    
    	private ContaDAO contaDAO;
    
    	public ContaRN() {
    		this.contaDAO = DAOFactory.criarContaDAO();
    	}
    
    	public List<Conta> listar(Usuario usuario) {
    		return this.contaDAO.listar(usuario);
    	}
    
    	public Conta carregar(Integer conta) {
    		return this.contaDAO.carregar(conta);
    	}
    
    	public void salvar(Conta conta) {
    		conta.setDataCadastro(new Date());
    		this.contaDAO.salvar(conta);
    	}
    
    	public void excluir(Conta conta) {
    		this.contaDAO.excluir(conta);
    	}
    
    	public void tornarFavorita(Conta contaFavorita) { 
    		Conta conta = this.buscarFavorita(contaFavorita.getUsuario());
    		if (conta != null) {
    			conta.setFavorita(false);
    			this.contaDAO.salvar(conta);
    		}
    
    		contaFavorita.setFavorita(true);
    		this.contaDAO.salvar(contaFavorita);
    	}
    
    	public Conta buscarFavorita(Usuario usuario) {
    		return this.contaDAO.buscarFavorita(usuario);
    	}
    }
    Classe ContaBean
    Java Code:
    package financeiro.web;
    
    import java.util.List;
    
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
    
    import financeiro.conta.Conta;
    import financeiro.conta.ContaRN;
    import financeiro.web.util.ContextoUtil;
    
    @ManagedBean(name="contaBean")
    @RequestScoped
    public class ContaBean {
    
    private Conta selecionada = new Conta();
    private List<Conta> lista = null;
    
    public void salvar(){
    	ContextoBean contextoBean = ContextoUtil.getContextoBean();
    	this.selecionada.setUsuario(contextoBean.getUsuarioLogado());
    	ContaRN contaRN = new ContaRN();
    	contaRN.salvar(this.selecionada);
    	this.selecionada = new Conta();
    	this.lista = null;
    }
    
    public void editar(){
    	
    }
    
    public void excluir(){
    	ContaRN contaRN = new ContaRN();
    	contaRN.excluir(this.selecionada);
    	this.selecionada = new Conta();
    	this.lista = null;
    }
    
    public void tornarFavorita(){
    	ContaRN contaRN = new ContaRN();
    	contaRN.tornarFavorita(this.selecionada);
    	this.selecionada = new Conta();
    }
    
    	public Conta getSelecionada() {
    		return selecionada;
    	}
    
    	public void setSelecionada(Conta selecionada) {
    		this.selecionada = selecionada;
    	}
    
    	public List<Conta> getLista() {
    		if(this.lista == null){
    			ContextoBean contextoBean = ContextoUtil.getContextoBean();
    			ContaRN contaRN = new ContaRN();
    			this.lista = contaRN.listar(contextoBean.getUsuarioLogado());
    		}
    		
    		return this.lista;
    	}
    
    	public void setLista(List<Conta> lista) {
    		this.lista = lista;
    	}
    	
    	
    	
    }
    Classe UsuarioBean (onde eu inserir a opçao de cadastrar conta na hora do registro de usuario.

    Java Code:
    package financeiro.web;
    
    import java.util.List;
    
    import javax.faces.application.FacesMessage;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
    import javax.faces.context.FacesContext;
    
    import financeiro.conta.Conta;
    import financeiro.conta.ContaRN;
    import financeiro.usuario.Usuario;
    import financeiro.usuario.UsuarioRN;
    
    @ManagedBean(name = "usuarioBean")
    @RequestScoped
    public class UsuarioBean {
    
    
    	public Conta getConta() {
    		return conta;
    	}
    
    	public void setConta(Conta conta) {
    		this.conta = conta;
    	}
    
    	public void setLista(List<Usuario> lista) {
    		this.lista = lista;
    	}
    
    	private Usuario usuario = new Usuario();
    	private String confirmarSenha;
    	private List<Usuario> lista;
    	private String destinoSalvar;
    	private Conta conta = new Conta();
    
    	public String novo() {
    		this.destinoSalvar = "usuarioSucesso";
    		this.usuario = new Usuario();
    		this.usuario.setAtivo(true);
    		return "usuario";
    
    	}
    
    	public String editar(){
    		this.confirmarSenha = this.usuario.getSenha();
    		return "/publico/usuario";
    	}
    	
    	public String salvar() {
    		FacesContext context = FacesContext.getCurrentInstance();
    
    		String senha = this.usuario.getSenha();
    		if (!senha.equals(this.confirmarSenha)) {
    			FacesMessage facesMessage = new FacesMessage(
    					"A senha não foi informada corretamente");
    			context.addMessage(null, facesMessage);
    			return null;
    		}
    		UsuarioRN usuarioRN = new UsuarioRN();
    		usuarioRN.salvar(this.usuario);
    		
    		if(this.conta.getDescricao() != null){
    			this.conta.setUsuario(this.usuario);
    			this.conta.setFavorita(true);
    			ContaRN contaRN = new ContaRN();
    			contaRN.salvar(this.conta);
    		}
    		return this.destinoSalvar;
    	}
    	
    	public String excluir(){
    		UsuarioRN usuarioRN = new UsuarioRN();
    		usuarioRN.excluir(this.usuario);
    		this.lista = null;
    		return null;
    	}
    	
    	public String ativar(){
    		if(this.usuario.isAtivo()){
    			this.usuario.setAtivo(false);
    		} else {
    			this.usuario.setAtivo(true);
    		}
    			UsuarioRN usuarioRN = new UsuarioRN();
    			usuarioRN.salvar(this.usuario);
    			return null;
    	}
    	
    	public List<Usuario> getLista(){
    		if(this.lista == null){
    			UsuarioRN usuarioRN = new UsuarioRN();
    			this.lista = usuarioRN.listar();
    		}
    		return this.lista;
    	}
    	
    	public String atribuirPermissao(Usuario usuario, String permissao){
    		this.usuario = usuario;
    		java.util.Set<String> permissoes = this.usuario.getPermissao();
    		if(permissoes.contains(permissao)){
    			permissoes.remove(permissao);
    		} else {
    			permissoes.add(permissao);
    		}
    		return null;
    	}
    
    	
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result
    				+ ((confirmarSenha == null) ? 0 : confirmarSenha.hashCode());
    		result = prime * result + ((conta == null) ? 0 : conta.hashCode());
    		result = prime * result
    				+ ((destinoSalvar == null) ? 0 : destinoSalvar.hashCode());
    		result = prime * result + ((lista == null) ? 0 : lista.hashCode());
    		result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
    		return result;
    	}
    	
    	@Override
    	public boolean equals(Object obj) {
    		if (this == obj)
    			return true;
    		if (obj == null)
    			return false;
    		if (getClass() != obj.getClass())
    			return false;
    		UsuarioBean other = (UsuarioBean) obj;
    		if (confirmarSenha == null) {
    			if (other.confirmarSenha != null)
    				return false;
    		} else if (!confirmarSenha.equals(other.confirmarSenha))
    			return false;
    		if (conta == null) {
    			if (other.conta != null)
    				return false;
    		} else if (!conta.equals(other.conta))
    			return false;
    		if (destinoSalvar == null) {
    			if (other.destinoSalvar != null)
    				return false;
    		} else if (!destinoSalvar.equals(other.destinoSalvar))
    			return false;
    		if (lista == null) {
    			if (other.lista != null)
    				return false;
    		} else if (!lista.equals(other.lista))
    			return false;
    		if (usuario == null) {
    			if (other.usuario != null)
    				return false;
    		} else if (!usuario.equals(other.usuario))
    			return false;
    		return true;
    	}
    
    	public Usuario getUsuario() {
    		return usuario;
    	}
    
    	public void setUsuario(Usuario usuario) {
    		this.usuario = usuario;
    	}
    
    	public String getConfirmarSenha() {
    		return confirmarSenha;
    	}
    
    	public void setConfirmarSenha(String confirmarSenha) {
    		this.confirmarSenha = confirmarSenha;
    	}
    
    	public String getDestinoSalvar() {
    		return destinoSalvar;
    	}
    	
    	public void setDestinoSalvar(String destinoSalvar) {
    		this.destinoSalvar = destinoSalvar;
    	}
    	
    	
    }
    e os JSF
    Tela de cadastro de conta
    Java Code:
    <?xml version="1.0" encoding="UTF-8" ?>
    <!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"
    	xmlns:sec="http://www.springframework.org/security/facelets/tags">
    <h:head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    	<title>Cadastro de Contas</title>
    </h:head>
    <h:body>
    	<h1>Cadastro de Contas</h1>
    	<h:form id="edicao">
    		<h:messages />
    		<h:inputHidden value="#{contaBean.selecionada.conta }" />
    		<h:inputHidden value="#{contaBean.selecionada.favorita }" />
    		<h:panelGrid columns="2">
    			<h:outputLabel value="Descrição: " for="descricao" />
    			<h:inputText id="descricao"
    				value="#{contaBean.selecionada.descricao }" required="true"
    				maxLength="45" />
    			<h:outputLabel value="Saldo Inicial: " for="saldoInicial" />
    			<h:inputText id="saldoInicial"
    				value="#{contaBean.selecionada.saldoInicial }" size="10">
    				<f:convertNumber minFractionDigits="2" />
    			</h:inputText>
    			<h:commandButton value="Salvar" action="#{contaBean.salvar }">
    				<f:ajax excute="@form" render=":edicao :listagem" />
    			</h:commandButton>
    		</h:panelGrid>
    
    
    	</h:form>
    
    	<h:form id="listagem">
    		<h:dataTable value="#{contaBean.lista }" var="conta"
    			rendered="#{!empty contaBean.lista }">
    			<h:column>
    				<f:facet name="header">Descrição</f:facet>
    			#{conta.descricao}
    			</h:column>
    			<h:column>
    				<f:facet name="header">Data Cadastro</f:facet>
    				<h:outputText value="#{conta.dataCadastro }">
    					<f:convertDateTime pattern="dd/MM/yyyy" />
    				</h:outputText>
    			</h:column>
    			<h:column>
    				<f:facet name="header">Saldo Inicial</f:facet>
    				<h:outputText value="#{ conta.saldoInicial}"
    					style="text-align: right; display:block;">
    					<f:convertNumber minFractionDigits="2" />
    				</h:outputText>
    			</h:column>
    			<h:column>
    				<h:commandLink action="#{contaBean.tornarFavorita }">
    					<f:ajax execute="@this" render=":listagem" />
    					<h:graphicImage library="imagens"
    						name="favorita16_#{conta.favorita }.png" />
    					<f:setPropertyActionListener value="#{conta }"
    						target="#{contaBean.selecionada }" />
    				</h:commandLink>
    			</h:column>
    			<h:column>
    				<h:commandLink>
    					<f:ajax execute="@this" render=":edicao" />
    					<h:graphicImage library="imagens" name="editar16.png" />
    					<f:setPropertyActionListener value="#{conta }"
    						target="#{contaBean.selecionada }" />
    				</h:commandLink>
    			</h:column>
    			<h:column>
    				<h:commandLink action="#{contaBean.excluir }">
    					<f:ajax execute="@this" render=":listagem" />
    					<h:graphicImage library="imagens" name="excluir16.png" />
    					<f:setPropertyActionListener value="#{conta }"
    						target="#{contaBean.selecionada }" />
    				</h:commandLink>
    			</h:column>
    		</h:dataTable>
    	</h:form>
    
    </h:body>
    </html>
    E no cadastro de usuario

    Java Code:
    <?xml version="1.0" encoding="UTF-8" ?>
    <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=ISO-8859-1" />
    	<title>Cadasro de Usuarios</title>
    </h:head>
    <h:body>
    	<h1>Cadastro de Usuários</h1>
    
    	<h:form id="cadastro">
    		<h:messages />
    		<h:inputHidden value="#{usuarioBean.usuario.codigo }" />
    		<h:inputHidden value="#{usuarioBean.usuario.ativo }" />
    		<h:inputHidden value="#{usuarioBean.destinoSalvar}" />
    
    		<h:panelGrid columns="2">
    			<h:outputLabel value="Nome" for="nome" />
    			<h:inputText id="nome" Label="Nome"
    				value="#{usuarioBean.usuario.nome }" size="30" maxLength="30"
    				required="true" requiredMessage="Por favor, insira um nome">
    				<f:validateLength minimum="10" maximum="30" />
    			</h:inputText>
    			<h:outputLabel value="Data Nascimento" for="data" />
    			<h:inputText id="data" label="Data Nascimento"
    				value="#{usuarioBean.usuario.nascimento}" size="10" maxlength="10"
    				required="false">
    				<f:convertDateTime pattern="dd/MM/yyyy" />
    			</h:inputText>
    			<h:outputLabel value="Celular" for="celular" />
    			<h:inputText id="celular" label="Celular"
    				value="#{usuarioBean.usuario.celular}" size="10" />
    			<h:outputLabel value="E-mail" for="email" />
    			<h:panelGroup>
    				<h:inputText id="email" label="E-mail"
    					value="#{usuarioBean.usuario.email}" size="50" required="true"
    					validatorMessage="e-mail inválido">
    					<f:validateRegex pattern="[a-zA-Z0-9\-\_\.]+@[a-zA-Z0-9\-\_\.]+" />
    				</h:inputText>
    				<h:message for="email" />
    			</h:panelGroup>
    
    			<h:outputLabel value="Idioma" for="idioma" />
    			<h:selectOneMenu id="idioma" value="#{usuarioBean.usuario.idioma}">
    				<f:selectItem itemValue="pt_BR" itemLabel="Português" />
    				<f:selectItem itemValue="en_US" itemLabel="English" />
    				<f:selectItem itemValue="es_ES" itemLabel="Espanol" />
    			</h:selectOneMenu>
    
    			<h:outputLabel value="Login" for="login" />
    			<h:inputText id="login" label="Login"
    				value="#{usuarioBean.usuario.login}" size="15" maxlength="15"
    				required="true"
    				validatorMessage="Login deve ter no minimo 5 e no máximo 15 caracteres, e só pode ter simbolos '.' e '_'. ">
    				<f:validateRegex pattern="([a-z]|[0-9]|[.]|[_]){2,15}" />
    			</h:inputText>
    
    			<h:outputLabel value="Senha" for="senha" />
    			<h:inputSecret id="senha" label="Senha"
    				value="#{usuarioBean.usuario.senha}" size="10" maxlength="10"
    				required="true" redisplay="true" />
    
    			<h:outputLabel value="Confirmar senha" for="confirmarSenha" />
    			<h:inputSecret id="confirmarSenha" label="Confirmar senha"
    				value="#{usuarioBean.confirmarSenha}" size="10" maxlength="10"
    				required="true" redisplay="true" />
    
    		</h:panelGrid>
    		<h:panelGroup rendered="#{empty contextoBean.usuarioLogado}">
    		<fieldset><legend>Conta Inicial</legend>
    		<h:panelGrid columns="2">
    		
    		<h:outputLabel value="Descrição" for="descricao" />
    		<h:inputText id="descricao" label="Descrição" value="#{usuarioBean.conta.descricao}" required="true" maxlength="45" />
    		<h:outputLabel value="Saldo inicial" for="saldoInicial" />
    		<h:inputText id="saldoInicial" label="Saldo Inicial" value="#{usuarioBean.conta.saldoInicial}" size="10">
    		<f:convertNumber minFractionDigits="2" />
    		</h:inputText>
    		</h:panelGrid>
    		
    		</fieldset>
    		</h:panelGroup>
    		<h:commandButton action="#{usuarioBean.salvar}" value="Salvar" />
    		
    		
    	</h:form>
    
    </h:body>
    </html>
    Thank you very much.

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Problem with hibernate insert

    That's way too much for anyone to go through, especially since I suspect not many of us can read Portuguese (I don't think I can even order a beer in it).

    You need to narrow it down.
    Debug when you are creating those other accounts from the accounts screen and see what values are being put into things, before they get persisted to the database. Then you might be able to reduce the code dump.

  3. #3
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Re: Problem with hibernate insert

    Hi Tolls, thank you for the reply
    I've did what you said, and the problems is.
    The hibernate is giving the insert command to the DB, but the DB is not saving the account.
    For the user i'v been using the session.save(obj) and for the account i'm using the saveOrUpdate(obj).
    Should i put my persistence code in here?
    or it's no use since i'm from Brasil?

    To order a beer you just have to say: "Quero uma cerveja!"
    Thank you very much.
    Regards.

  4. #4
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Problem with hibernate insert

    You can get hibernate to log the SQL it sends to the server.
    You'll have to dig up the docs on that, as I can never remember exactly which bits to switch on.

    What does your saveOrUpdate() method do?

  5. #5
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Re: Problem with hibernate insert

    Quote Originally Posted by Tolls View Post
    You can get hibernate to log the SQL it sends to the server.
    You'll have to dig up the docs on that, as I can never remember exactly which bits to switch on.

    What does your saveOrUpdate() method do?
    Hi, thanks again.
    this is my debug from hibernate

    Java Code:
    20:59:27.013 [http-bio-8080-exec-2] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13160447670  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG o.h.transaction.JDBCTransaction - begin  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG o.h.transaction.JDBCTransaction - current autocommit status: true  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG o.h.transaction.JDBCTransaction - disabling autocommit  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 1 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@5e687b94: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5e687b94: Principal: org.springframework.security.core.userdetails.User@34bf8c6f: Username: dennisbf; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USUARIO; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@1c07a: RemoteIpAddress: 127.0.0.1; SessionId: 670ABE1C0A0E43B9F67C63B7383C7176; Granted Authorities: ROLE_USUARIO'  
    20:59:27.014 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 2 of 10 in additional filter chain; firing Filter: 'LogoutFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 3 of 10 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 4 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 5 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 6 of 10 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.r.RememberMeAuthenticationFilter - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5e687b94: Principal: org.springframework.security.core.userdetails.User@34bf8c6f: Username: dennisbf; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USUARIO; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@1c07a: RemoteIpAddress: 127.0.0.1; SessionId: 670ABE1C0A0E43B9F67C63B7383C7176; Granted Authorities: ROLE_USUARIO'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 7 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5e687b94: Principal: org.springframework.security.core.userdetails.User@34bf8c6f: Username: dennisbf; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USUARIO; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@1c07a: RemoteIpAddress: 127.0.0.1; SessionId: 670ABE1C0A0E43B9F67C63B7383C7176; Granted Authorities: ROLE_USUARIO'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 8 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 9 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf at position 10 of 10 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/restrito/conta.jsf'; against '/admin/**'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/restrito/conta.jsf'; against '/restrito/**'  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /restrito/conta.jsf; Attributes: [ROLE_USUARIO]  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5e687b94: Principal: org.springframework.security.core.userdetails.User@34bf8c6f: Username: dennisbf; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USUARIO; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@1c07a: RemoteIpAddress: 127.0.0.1; SessionId: 670ABE1C0A0E43B9F67C63B7383C7176; Granted Authorities: ROLE_USUARIO  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.access.vote.RoleVoter@100c405f, returned: 1  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object  
    20:59:27.015 [http-bio-8080-exec-2] DEBUG o.s.security.web.FilterChainProxy - /restrito/conta.jsf reached end of additional filter chain; proceeding with original chain  
    20:59:27.023 [http-bio-8080-exec-2] DEBUG o.h.e.def.AbstractSaveEventListener - executing identity-insert immediately  
    20:59:27.023 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)  
    20:59:27.023 [http-bio-8080-exec-2] DEBUG org.hibernate.SQL -   
        insert   
        into  
            conta_bancaria  
            (dat_cadastro, des_conta, favorita, saldo_inicial, cod_usuario)   
        values  
            (?, ?, ?, ?, ?)  
    Hibernate:   
        insert   
        into  
            conta_bancaria  
            (dat_cadastro, des_conta, favorita, saldo_inicial, cod_usuario)   
        values  
            (?, ?, ?, ?, ?)  
    20:59:27.025 [http-bio-8080-exec-2] DEBUG o.h.id.IdentifierGeneratorHelper - Natively generated identity: 6  
    20:59:27.025 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)  
    20:59:27.032 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades  
    20:59:27.032 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections  
    20:59:27.033 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 insertions, 0 updates, 0 deletions to 1 objects  
    20:59:27.033 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections  
    20:59:27.033 [http-bio-8080-exec-2] DEBUG org.hibernate.pretty.Printer - listing entities:  
    20:59:27.033 [http-bio-8080-exec-2] DEBUG org.hibernate.pretty.Printer - financeiro.conta.Conta{saldoInicial=0.0, usuario=financeiro.usuario.Usuario#1, favorita=false, conta=6, descricao=null, dataCadastro=Wed Sep 14 20:59:27 BRT 2011}  
    20:59:27.033 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)  
    20:59:27.033 [http-bio-8080-exec-2] DEBUG org.hibernate.SQL -   
        select  
            this_.cod_conta as cod1_1_1_,  
            this_.dat_cadastro as dat2_1_1_,  
            this_.des_conta as des3_1_1_,  
            this_.favorita as favorita1_1_,  
            this_.saldo_inicial as saldo5_1_1_,  
            this_.cod_usuario as cod6_1_1_,  
            usuario2_.codigo as codigo0_0_,  
            usuario2_.ativo as ativo0_0_,  
            usuario2_.celular as celular0_0_,  
            usuario2_.email as email0_0_,  
            usuario2_.idioma as idioma0_0_,  
            usuario2_.login as login0_0_,  
            usuario2_.nascimento as nascimento0_0_,  
            usuario2_.nome as nome0_0_,  
            usuario2_.senha as senha0_0_   
        from  
            conta_bancaria this_   
        inner join  
            Usuario usuario2_   
                on this_.cod_usuario=usuario2_.codigo   
        where  
            this_.cod_usuario=?  
    Hibernate:   
        select  
            this_.cod_conta as cod1_1_1_,  
            this_.dat_cadastro as dat2_1_1_,  
            this_.des_conta as des3_1_1_,  
            this_.favorita as favorita1_1_,  
            this_.saldo_inicial as saldo5_1_1_,  
            this_.cod_usuario as cod6_1_1_,  
            usuario2_.codigo as codigo0_0_,  
            usuario2_.ativo as ativo0_0_,  
            usuario2_.celular as celular0_0_,  
            usuario2_.email as email0_0_,  
            usuario2_.idioma as idioma0_0_,  
            usuario2_.login as login0_0_,  
            usuario2_.nascimento as nascimento0_0_,  
            usuario2_.nome as nome0_0_,  
            usuario2_.senha as senha0_0_   
        from  
            conta_bancaria this_   
        inner join  
            Usuario usuario2_   
                on this_.cod_usuario=usuario2_.codigo   
        where  
            this_.cod_usuario=?  
    20:59:27.034 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0)  
    20:59:27.035 [http-bio-8080-exec-2] DEBUG org.hibernate.loader.Loader - result row: EntityKey[financeiro.usuario.Usuario#1], EntityKey[financeiro.conta.Conta#5]  
    20:59:27.036 [http-bio-8080-exec-2] DEBUG org.hibernate.loader.Loader - result row: EntityKey[financeiro.usuario.Usuario#1], EntityKey[financeiro.conta.Conta#6]  
    20:59:27.036 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1)  
    20:59:27.036 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)  
    20:59:27.036 [http-bio-8080-exec-2] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [financeiro.usuario.Usuario#1]  
    20:59:27.036 [http-bio-8080-exec-2] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [financeiro.usuario.Usuario#1]  
    20:59:27.036 [http-bio-8080-exec-2] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [financeiro.conta.Conta#5]  
    20:59:27.037 [http-bio-8080-exec-2] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [financeiro.conta.Conta#5]  
    20:59:27.037 [http-bio-8080-exec-2] DEBUG o.h.e.StatefulPersistenceContext - initializing non-lazy collections  
    20:59:27.048 [http-bio-8080-exec-2] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally  
    20:59:27.048 [http-bio-8080-exec-2] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed  
    20:59:27.048 [http-bio-8080-exec-2] DEBUG o.h.transaction.JDBCTransaction - commit  
    20:59:27.048 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades  
    20:59:27.048 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG org.hibernate.engine.Collections - Collection found: [financeiro.usuario.Usuario.permissao#1], was: [financeiro.usuario.Usuario.permissao#1] (uninitialized)  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 insertions, 0 updates, 0 deletions to 3 objects  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 1 collections  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG org.hibernate.pretty.Printer - listing entities:  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG org.hibernate.pretty.Printer - financeiro.conta.Conta{saldoInicial=0.0, usuario=financeiro.usuario.Usuario#1, favorita=false, conta=5, descricao=null, dataCadastro=2011-09-14 20:58:22.0}  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG org.hibernate.pretty.Printer - financeiro.conta.Conta{saldoInicial=0.0, usuario=financeiro.usuario.Usuario#1, favorita=false, conta=6, descricao=null, dataCadastro=Wed Sep 14 20:59:27 BRT 2011}  
    20:59:27.049 [http-bio-8080-exec-2] DEBUG org.hibernate.pretty.Printer - financeiro.usuario.Usuario{codigo=1, email=dennisbf@gmail.com, ativo=true, idioma=pt_BR, nome=Dennis Faggiani, nascimento=1982-02-23 21:00:00.0, login=dennisbf, senha=de24pi14, permissao=<uninitialized>, celular=1178215758}  
    20:59:27.050 [http-bio-8080-exec-2] DEBUG o.h.transaction.JDBCTransaction - re-enabling autocommit  
    20:59:27.050 [http-bio-8080-exec-2] DEBUG o.h.transaction.JDBCTransaction - committed JDBC Connection  
    20:59:27.050 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection  
    20:59:27.050 [http-bio-8080-exec-2] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]  
    20:59:27.051 [http-bio-8080-exec-2] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13160447670
    and this is where my saveOrUpdate is

    Java Code:
    package financeiro.conta;
    
    import java.util.List;
    
    import org.hibernate.Criteria;
    import org.hibernate.Session;
    import org.hibernate.criterion.Restrictions;
    
    import financeiro.usuario.Usuario;
    
    public class ContaDAOHibernate implements ContaDAO {
    
    	private Session	session;
    
    	public void setSession(Session session) {
    		this.session = session;
    	}
    
    	@Override
    	public void excluir(Conta conta) {
    		this.session.delete(conta);
    	}
    
    	@Override
    	public void salvar(Conta conta) {
    		this.session.saveOrUpdate(conta);
    	}
    
    	@Override
    	public Conta carregar(Integer conta) {
    		return (Conta) this.session.get(Conta.class, conta);
    	}
    
    	@SuppressWarnings("unchecked")
    	@Override
    	public List<Conta> listar(Usuario usuario) {
    
    		Criteria criteria = this.session.createCriteria(Conta.class);
    		criteria.add(Restrictions.eq("usuario", usuario));
    
    		return criteria.list();
    	}
    
    	@Override
    	public Conta buscarFavorita(Usuario usuario) {
    
    		Criteria criteria = this.session.createCriteria(Conta.class);
    		criteria.add(Restrictions.eq("usuario", usuario));
    		criteria.add(Restrictions.eq("favorita", true));
    
    		return (Conta) criteria.uniqueResult();
    	}
    }
    If it is a new account he suposed to create, if the account already exists he suposed to update it.

    Thank you very much.

  6. #6
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Problem with hibernate insert

    Java Code:
    	public void salvar(Conta conta) {
    		this.session.saveOrUpdate(conta);
    	}
    Log the state of conta before saving.

  7. #7
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Re: Problem with hibernate insert

    Hi, i'm not sure if i understood what i said but. This is my log the account pages, without save any account.

    Java Code:
    12:28:33.621 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
    12:28:33.625 [http-bio-8080-exec-9] DEBUG org.hibernate.SQL - 
        select
            usuario0_.codigo as codigo0_,
            usuario0_.ativo as ativo0_,
            usuario0_.celular as celular0_,
            usuario0_.email as email0_,
            usuario0_.idioma as idioma0_,
            usuario0_.login as login0_,
            usuario0_.nascimento as nascimento0_,
            usuario0_.nome as nome0_,
            usuario0_.senha as senha0_ 
        from
            Usuario usuario0_ 
        where
            usuario0_.login=?
    Hibernate: 
        select
            usuario0_.codigo as codigo0_,
            usuario0_.ativo as ativo0_,
            usuario0_.celular as celular0_,
            usuario0_.email as email0_,
            usuario0_.idioma as idioma0_,
            usuario0_.login as login0_,
            usuario0_.nascimento as nascimento0_,
            usuario0_.nome as nome0_,
            usuario0_.senha as senha0_ 
        from
            Usuario usuario0_ 
        where
            usuario0_.login=?
    12:28:33.627 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0)
    12:28:33.635 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - result row: EntityKey[financeiro.usuario.Usuario#1]
    12:28:33.643 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1)
    12:28:33.644 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    12:28:33.644 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [financeiro.usuario.Usuario#1]
    12:28:33.655 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [financeiro.usuario.Usuario#1]
    12:28:33.655 [http-bio-8080-exec-9] DEBUG o.h.e.StatefulPersistenceContext - initializing non-lazy collections
    12:28:33.669 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades
    12:28:33.671 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections
    12:28:33.704 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.Collections - Collection found: [financeiro.usuario.Usuario.permissao#1], was: [financeiro.usuario.Usuario.permissao#1] (uninitialized)
    12:28:33.704 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 insertions, 0 updates, 0 deletions to 1 objects
    12:28:33.704 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 1 collections
    12:28:33.705 [http-bio-8080-exec-9] DEBUG org.hibernate.pretty.Printer - listing entities:
    12:28:33.705 [http-bio-8080-exec-9] DEBUG org.hibernate.pretty.Printer - financeiro.usuario.Usuario{codigo=1, email=dennisbf@gmail.com, ativo=true, idioma=pt_BR, nome=Dennis Faggiani, nascimento=1982-02-23 21:00:00.0, login=dennisbf, senha=de24pi14, permissao=<uninitialized>, celular=1178215758}
    12:28:33.706 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
    12:28:33.709 [http-bio-8080-exec-9] DEBUG org.hibernate.SQL - 
        select
            this_.cod_conta as cod1_1_1_,
            this_.dat_cadastro as dat2_1_1_,
            this_.des_conta as des3_1_1_,
            this_.favorita as favorita1_1_,
            this_.saldo_inicial as saldo5_1_1_,
            this_.cod_usuario as cod6_1_1_,
            usuario2_.codigo as codigo0_0_,
            usuario2_.ativo as ativo0_0_,
            usuario2_.celular as celular0_0_,
            usuario2_.email as email0_0_,
            usuario2_.idioma as idioma0_0_,
            usuario2_.login as login0_0_,
            usuario2_.nascimento as nascimento0_0_,
            usuario2_.nome as nome0_0_,
            usuario2_.senha as senha0_0_ 
        from
            conta_bancaria this_ 
        inner join
            Usuario usuario2_ 
                on this_.cod_usuario=usuario2_.codigo 
        where
            this_.cod_usuario=?
    Hibernate: 
        select
            this_.cod_conta as cod1_1_1_,
            this_.dat_cadastro as dat2_1_1_,
            this_.des_conta as des3_1_1_,
            this_.favorita as favorita1_1_,
            this_.saldo_inicial as saldo5_1_1_,
            this_.cod_usuario as cod6_1_1_,
            usuario2_.codigo as codigo0_0_,
            usuario2_.ativo as ativo0_0_,
            usuario2_.celular as celular0_0_,
            usuario2_.email as email0_0_,
            usuario2_.idioma as idioma0_0_,
            usuario2_.login as login0_0_,
            usuario2_.nascimento as nascimento0_0_,
            usuario2_.nome as nome0_0_,
            usuario2_.senha as senha0_0_ 
        from
            conta_bancaria this_ 
        inner join
            Usuario usuario2_ 
                on this_.cod_usuario=usuario2_.codigo 
        where
            this_.cod_usuario=?
    12:28:33.713 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0)
    12:28:33.713 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - result row: EntityKey[financeiro.usuario.Usuario#1], EntityKey[financeiro.conta.Conta#5]
    12:28:33.714 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - result row: EntityKey[financeiro.usuario.Usuario#1], EntityKey[financeiro.conta.Conta#6]
    12:28:33.714 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1)
    12:28:33.714 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    12:28:33.714 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [financeiro.conta.Conta#5]
    12:28:33.716 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [financeiro.conta.Conta#5]
    12:28:33.716 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [financeiro.conta.Conta#6]
    12:28:33.716 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [financeiro.conta.Conta#6]
    12:28:33.716 [http-bio-8080-exec-9] DEBUG o.h.e.StatefulPersistenceContext - initializing non-lazy collections
    12:28:33.719 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - loading collection: [financeiro.usuario.Usuario.permissao#1]
    12:28:33.719 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
    12:28:33.719 [http-bio-8080-exec-9] DEBUG org.hibernate.SQL - 
        select
            permissao0_.usuario as usuario0_0_,
            permissao0_.permissao as permissao0_ 
        from
            usuario_permissao permissao0_ 
        where
            permissao0_.usuario=?
    Hibernate: 
        select
            permissao0_.usuario as usuario0_0_,
            permissao0_.permissao as permissao0_ 
        from
            usuario_permissao permissao0_ 
        where
            permissao0_.usuario=?
    12:28:33.719 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0)
    12:28:33.719 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - result set contains (possibly empty) collection: [financeiro.usuario.Usuario.permissao#1]
    12:28:33.721 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - result row: 
    12:28:33.721 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - found row of collection: [financeiro.usuario.Usuario.permissao#1]
    12:28:33.722 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1)
    12:28:33.722 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    12:28:33.722 [http-bio-8080-exec-9] DEBUG o.h.e.loading.CollectionLoadContext - 1 collections were found in result set for role: financeiro.usuario.Usuario.permissao
    12:28:33.722 [http-bio-8080-exec-9] DEBUG o.h.e.loading.CollectionLoadContext - collection fully initialized: [financeiro.usuario.Usuario.permissao#1]
    12:28:33.722 [http-bio-8080-exec-9] DEBUG o.h.e.loading.CollectionLoadContext - 1 collections initialized for role: financeiro.usuario.Usuario.permissao
    12:28:33.722 [http-bio-8080-exec-9] DEBUG o.h.e.StatefulPersistenceContext - initializing non-lazy collections
    12:28:33.722 [http-bio-8080-exec-9] DEBUG org.hibernate.loader.Loader - done loading collection
    12:28:33.724 [http-bio-8080-exec-9] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
    12:28:33.725 [http-bio-8080-exec-9] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
    12:28:33.725 [http-bio-8080-exec-9] DEBUG o.h.transaction.JDBCTransaction - commit
    12:28:33.725 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades
    12:28:33.725 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections
    12:28:33.725 [http-bio-8080-exec-9] DEBUG org.hibernate.engine.Collections - Collection found: [financeiro.usuario.Usuario.permissao#1], was: [financeiro.usuario.Usuario.permissao#1] (initialized)
    12:28:33.725 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 insertions, 0 updates, 0 deletions to 3 objects
    12:28:33.725 [http-bio-8080-exec-9] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 1 collections
    12:28:33.725 [http-bio-8080-exec-9] DEBUG org.hibernate.pretty.Printer - listing entities:
    12:28:33.725 [http-bio-8080-exec-9] DEBUG org.hibernate.pretty.Printer - financeiro.conta.Conta{saldoInicial=0.0, usuario=financeiro.usuario.Usuario#1, favorita=false, conta=5, descricao=null, dataCadastro=2011-09-14 20:58:22.0}
    12:28:33.725 [http-bio-8080-exec-9] DEBUG org.hibernate.pretty.Printer - financeiro.conta.Conta{saldoInicial=0.0, usuario=financeiro.usuario.Usuario#1, favorita=false, conta=6, descricao=null, dataCadastro=2011-09-14 20:59:27.0}
    12:28:33.726 [http-bio-8080-exec-9] DEBUG org.hibernate.pretty.Printer - financeiro.usuario.Usuario{codigo=1, email=dennisbf@gmail.com, ativo=true, idioma=pt_BR, nome=Dennis Faggiani, nascimento=1982-02-23 21:00:00.0, login=dennisbf, senha=de24pi14, permissao=[ROLE_USUARIO], celular=1178215758}
    12:28:33.727 [http-bio-8080-exec-9] DEBUG o.h.transaction.JDBCTransaction - re-enabling autocommit
    12:28:33.727 [http-bio-8080-exec-9] DEBUG o.h.transaction.JDBCTransaction - committed JDBC Connection
    12:28:33.727 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
    12:28:33.727 [http-bio-8080-exec-9] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
    12:28:33.727 [http-bio-8080-exec-9] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13161005137
    Thank you.

    One thing thant i find wierd, is that he try to get "Usuario2" (user2), but i just have 1 user registered.
    Thank you again.

  8. #8
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Problem with hibernate insert

    You're saying (from the OP) that some of your details in the account table are not being saved (ie null).
    The only way that can happen is if the account objects that Hibernate is being asked to persist do not have those values in them (presuming the Hibernate mapping is correct, which I would say it is since other account rows save correctly).

    If that is not the problem then you'll have to explain simply and possibly without such massive log dumps.

  9. #9
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Re: Problem with hibernate insert

    Hmm, that mapping is correct, but i've notice that the order in the DB, is diferent from the one that Hibernate is inserting


    my DB is like this
    cod_conta, cod_usuario, des_conta, dat_cadastro, sal_inicial_favorita

    and how hibernate is inserting
    dat_cadastro, des_conta, favorita, saldo_inicial, cod_usuario

    Thank you

  10. #10
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Problem with hibernate insert

    This is Hibernate's insert statement:
    Java Code:
        insert   
        into  
            conta_bancaria  
            (dat_cadastro, des_conta, favorita, saldo_inicial, cod_usuario)   
        values  
            (?, ?, ?, ?, ?)
    It says what columns everything is inserting into.

    Have you logged the values in conta yet, before calling saveOrUpdate()? That's the only way you'll see what's up.
    I very (very) much doubt it's a Hibernate problem.

  11. #11
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Re: Problem with hibernate insert

    You're right, Tolls.
    Is not Hibernate problem, here's what i getting now

    Java Code:
    SEVERE: /restrito/principal.xhtml @22,58 valueChangeListener="#{contextoBean.setContaAtiva}": java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    the only place where i call this method is here

    Java Code:
    <h:selectOneMenu value="#{contextoBean.getContaAtiva.conta}"  
                valueChangeListener="#{contextoBean.setContaAtiva}"  
                rendered="#{!empty contextoBean}" onchange="submit()">  
                <f:selectItems value="#{contaBean.lista}" var="conta"  
                    itemValue="#{conta.conta}" itemLabel="#{conta.descricao}" />  
            </h:selectOneMenu>
    and my setContaAtiva is here

    Java Code:
    public void setContaAtiva(ValueChangeEvent event){  
        Integer conta = (Integer) event.getNewValue();  
        ContaRN contaRN = new ContaRN();  
        this.contaAtiva = contaRN.carregar(conta);  
          
          
    }
    Thank you very much

  12. #12
    dennisbf is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default Re: Problem with hibernate insert

    it is because of the Class ContaRN who have a method called carregar

    Java Code:
    public Conta carregar(Integer conta) {  
        return this.contaDAO.carregar(conta);  
    }
    i'm studding from a book, and it don't explains quite well.
    But, i think that is because of the id of the account?

    Thank you very much

    Here is from where the method is called


    Conta
    Java Code:
    @Id
    	@GeneratedValue
    	@Column(name="cod_conta")
    	private Integer	conta;

    ContaDAO
    Java Code:
    public Conta carregar(Integer conta);
    Last edited by dennisbf; 09-15-2011 at 06:29 PM.

Similar Threads

  1. Replies: 3
    Last Post: 07-12-2010, 07:15 AM
  2. java insert data into database problem
    By chyeeqi in forum NetBeans
    Replies: 3
    Last Post: 03-29-2010, 01:36 AM
  3. Problem when insert Date to database(SQL)
    By hungleon88 in forum JDBC
    Replies: 6
    Last Post: 04-29-2009, 03:53 PM
  4. Replies: 3
    Last Post: 02-28-2009, 09:17 AM
  5. insert image to oracle using hibernate
    By Thennarasu in forum Advanced Java
    Replies: 12
    Last Post: 01-27-2009, 03:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •