Trouble with Hibernate

Asked

Viewed 295 times

0

I’m trying to learn about Hibernate together with a tutorial making an app for a petshop and I’m having the following problems:

INFO: HHH000228: Running hbm2ddl schema update
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.banho
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idservico]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_8bc8p6qj2ek64yrb76s976rjf]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.cachorro
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idpet]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_m1qtvr24qy5xjxnemmd9oic16]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.cliente
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [senha, tipo, nome, idcliente, email]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.consulta
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idservico]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_6qm9x1xxks3unkgaob3i99d03]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.docreceita
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [iddocreceita, tipo, numero, idcliente]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_j4avp8ra42thcbkyewl6b1k2h]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [fk_j4avp8ra42thcbkyewl6b1k2h, primary]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.endereco
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [uf, cidade, numero, bairro, lograd, idendereco, complement, idcliente, cep]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_be5ys2q5h8kp2jbo3na5i375h]
dez 16, 2015 8:34:52 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [fk_be5ys2q5h8kp2jbo3na5i375h, primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.gato
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idpet]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_griths664hfg8ouo2sno5nh2f]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.pf
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idcliente]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_qxjleuo0xbnb1tle975pj3j8e]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.pj
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idcliente]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_8w9emf3u9u8xwfs06kg7t3cn1]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> 
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.telefone
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [codarea, numero, idtelefone, idcliente]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> 
INFO: HHH000108: Foreign keys: [fk_8ebk7ukc8bu6le5maqc22j7fe]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [fk_8ebk7ukc8bu6le5maqc22j7fe, primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.tosa
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init> 
INFO: HHH000037: Columns: [idservico]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_i1bl4hfp3l6vxfaof4an77ixv]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.vacina
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [idservico]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_8hjpu55jfw6hofemns2b2q8v0]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.pet
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [obs, tipo, idpet, raca, nome, sexo, datanascimento, idcliente, descricao]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_p0g8vb4xgsxek1s5jao9u4prw]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [fk_p0g8vb4xgsxek1s5jao9u4prw, primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: petshop1.servico
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [data_dia, obs, tipo, idpet, valor, nome, idservico, descricao]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_lny299dytlemb03botpbk0f8b]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [fk_lny299dytlemb03botpbk0f8b, primary]
dez 16, 2015 8:34:53 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select cliente0_.idCliente as idClient2_2_, cliente0_.email as email3_2_, cliente0_.nome as nome4_2_, cliente0_.senha as senha5_2_, cliente0_.tipo as tipo1_2_ from Cliente cliente0_ left outer join PF cliente0_1_ on cliente0_.idCliente=cliente0_1_.idCliente left outer join PJ cliente0_2_ on cliente0_.idCliente=cliente0_2_.idCliente where cliente0_.email=? and cliente0_.senha=?
Erro na autenticação
Hibernate: select docreceita0_.idDocReceita as idDocRec2_4_, docreceita0_.idCliente as idClient4_4_, docreceita0_.numero as numero3_4_, docreceita0_.tipo as tipo1_4_ from DocReceita docreceita0_ where docreceita0_.numero=?
Hibernate: insert into Cliente (email, nome, senha, tipo) values (?, ?, ?, '1')
dez 16, 2015 8:34:55 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelperlogExceptions
WARN: SQL Error: 0, SQLState: S1009
dez 16, 2015 8:34:55 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelperlogExceptions
ERROR: Parameter index out of range (4 > number of parameters, which is 3).
org.hibernate.exception.GenericJDBCException: couldnotinsert[br.com.diego.controle.PF]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardS    QLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java    :126)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturnin    gDelegate.java:65)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPers    ister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPers    ister.java:3556)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityI    nsertAction.java:97)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:480)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.j    ava:191)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:175)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:210)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractS    aveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(Ab    stractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveE    ventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(Abstr    actSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedO    rRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequest    edId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(    DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(Defaul    tSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(Def    aultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
at br.com.diego.modelo.ClienteMTD.salvar(ClienteMTD.java:26)
at br.com.diego.controle.Cliente.salvar(Cliente.java:89)
at br.com.diego.modelo.TestandoHibernate.persistindo(TestandoHibernate.java:112)
at br.com.diego.modelo.TestandoHibernate.main(TestandoHibernate.java:32)
Caused by: java.sql.SQLException: Parameter index out of range (4 > number of parameters, which is 3).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3813)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3795)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3840)
at com.mysql.jdbc.PreparedStatement.setInt(PreparedStatement.java:3784)
at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$1.doBind(IntegerTypeDesc    riptor.java:64)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicTy    pe.java:282)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicTy    pe.java:277)
at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSin    gleColumnStandardBasicType.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityP    ersister.java:2843)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityP    ersister.java:2818)
at org.hibernate.persister.entity.AbstractEntityPersister$4.bindValues(AbstractEnti    tyPersister.java:3025)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturnin    gDelegate.java:57)
... 23 more

Client class.java :

package br.com.diego.controle;

import br.com.diego.modelo.ClienteMTD;
import java.io.Serializable; 
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.hibernate.annotations.*;


@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "tipo")
public abstract class Cliente implements Autenticavel, Serializable {

@Id 
@GeneratedValue(strategy = GenerationType.AUTO)
private int idCliente;

@Column(nullable = false, length = 2)
private int tipo;
@Column(nullable = false, length = 250)
private String nome;
@Column(nullable = false, length = 250)
private String email;
@Column(nullable = false, length = 250)
private String senha;

@OneToMany(mappedBy = "cliente", fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private Collection<Telefone> telefone;
@OneToMany(mappedBy = "cliente", fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private Collection<Endereco> endereco;
@OneToMany(mappedBy = "cliente", fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private Collection<Pet> pet;
@OneToOne(mappedBy = "cliente", fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private DocReceita docReceita;

public static int PF = 1;
public static int PJ = 2;


public Cliente() {
}

public Cliente(int idCliente, int tipo, String nome, Collection<Telefone>      telefone, Collection<Endereco> endereco, Collection<Pet> pet, String email,     String senha, DocReceita docReceita) {

    this.idCliente = idCliente;
    this.tipo = tipo;
    this.nome = nome;       
    this.telefone = telefone;
    this.endereco = endereco;
    this.pet = pet;
    this.email = email;
    this.senha = senha;
    this.docReceita = docReceita;

}

public Autenticavel autenticar(String usuario, String senha){
    return ClienteMTD.autenticar(usuario, senha);
    }

public boolean existe(String email){
    return ClienteMTD.existe(email);
    }

public boolean existe(DocReceita documento){
    return ClienteMTD.existe(documento);    
    }

static public boolean salvar(Cliente p){
    return ClienteMTD.salvar(p);
    }   

static public ArrayList<Cliente>consultar(){
    return ClienteMTD.consultar();
    }

static public Cliente consultar(int idCliente){
    return ClienteMTD.consultar(idCliente);
    }

static public Collection<Cliente> consultar(String nome){
    return ClienteMTD.consultar(nome);
    }

static public boolean alterar(Cliente p){
    return ClienteMTD.alterar(p);
    }

static public boolean excluir(Cliente p){
    return ClienteMTD.excluir(p);
    }

/**
 * @return the idCliente
 */
public int getIdCliente() {
    return idCliente;
}

/**
 * @param idCliente the idCliente to set
 */
public void setIdCliente(int idCliente) {
    this.idCliente = idCliente;
}

/**
 * @return the tipo
 */
public int getTipo() {
    return tipo;
}

/**
 * @param tipo the tipo to set
 */
public void setTipo(int tipo) {
    this.tipo = tipo;
}

/**
 * @return the nome
 */
public String getNome() {
    return nome;
}

/**
 * @param nome the nome to set
 */
public void setNome(String nome) {
    this.nome = nome;
}

/**
 * @return the telefone
 */
public Collection<Telefone> getTelefone() {
    return telefone;
}

/**
 * @param telefone the telefone to set
 */
public void setTelefone(Collection<Telefone> telefone) {
    this.telefone = telefone;
}

/**
 * @return the endereco
 */
public Collection<Endereco> getEndereco() {
    return endereco;
}

/**
 * @param endereco the endereco to set
 */
public void setEndereco(Collection<Endereco> endereco) {
    this.endereco = endereco;
}

/**
 * @return the pet
 */
public Collection<Pet> getPet() {
    return pet;
}

/**
 * @param pet the pet to set
 */
public void setPet(Collection<Pet> pet) {
    this.pet = pet;
}

/**
 * @return the email
 */
public String getEmail() {
    return email;
}

/**
 * @param email the email to set
 */
public void setEmail(String email) {
    this.email = email;
}

/**
 * @return the senha
 */
public String getSenha() {
    return senha;
}

/**
 * @param senha the senha to set
 */
public void setSenha(String senha) {
    this.senha = senha;
}

/**
 * @return the docReceita
 */
public DocReceita getDocReceita() {
    return docReceita;
}

/**
 * @param docReceita the docReceita to set
 */
public void setDocReceita(DocReceita docReceita) {
    this.docReceita = docReceita;
}
}

Clientemtd.java

package br.com.diego.modelo;

import br.com.diego.controle.Autenticavel;
import br.com.diego.controle.DocReceita;
import br.com.diego.controle.Cliente;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
*
* @author diego
*/
public class ClienteMTD {


public static boolean salvar(Cliente p) {
    Session session;
    session = HibernateUtil.getInstance();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        session.save(p);
        tx.commit();
        return true;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return false;
    } finally {
        session.close();
    }
}

public static Cliente consultar(int idCliente) {
    Session session;
    session = HibernateUtil.getInstance();
    Transaction tx = null;
    Cliente p = null;
    try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM Cliente as p where p.idCliente=:id");
        q.setParameter("id", idCliente);
        List resultados = q.list();
        if (resultados.size() > 0) {
            p = (Cliente) resultados.get(0);
        }
        return p;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return p;
    } finally {
        session.close();
    }
}

public static ArrayList<Cliente> consultar() {
    Session session;
    session = HibernateUtil.getInstance();
    Transaction tx = null;
    ArrayList<Cliente> p = null;
    try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM Cliente as p");
        p = (ArrayList<Cliente>) q.list();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
    }
    return p;
}

public static Collection<Cliente> consultar(String nome) {
    Session session;
    session = HibernateUtil.getInstance();
    Transaction tx = null;
    Collection<Cliente> p = null;
    try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM Cliente as p where p.nome=:nome");
        q.setParameter("nome", nome);
        p = q.list();
        return p;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return p;
    } finally {
        session.close();
    }
}

public static boolean alterar(Cliente p) {
    Session session = HibernateUtil.getInstance();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        session.merge(p);
        tx.commit();
        return true;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return false;
    } finally {
        session.close();
    }
}

public static boolean excluir(Cliente p) {
    Session session = HibernateUtil.getInstance();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        session.delete(p);
        tx.commit();
        return true;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return false;
    }
}

public static Autenticavel autenticar(String usuario, String senha) {
    Session session = HibernateUtil.getInstance();
    Transaction tx = null;
    Cliente p = null;
    try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM Cliente as p where p.email=:usuario and p.senha=:senha");
        q.setParameter("usuario", usuario);
        q.setParameter("senha", senha);
        List resultados = q.list();
        if (resultados.size() > 0) {
            p = (Cliente) resultados.get(0);
        }
        return p;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return p;
    } finally {
        session.close();
    }
}

public static boolean existe(String usuario) {
    Session session = HibernateUtil.getInstance();
    Transaction tx = null;
     try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM Cliente as p where p.email=:usuario");
        q.setParameter("usuario", usuario);
        List resultados = q.list();
        if (resultados.size() > 0) {
            return true;
        }else{
            return false;
        }
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        throw new RuntimeException("Erro ao consultar existência de usuário");
    } finally {
        session.close();
    }
}

public static boolean existe(DocReceita documento) {
    Session session = HibernateUtil.getInstance();
    Transaction tx = null;
     try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM DocReceita as d where d.numero=:documento");
        q.setParameter("documento", documento.getNumero());
        List resultados = q.list();
        if (resultados.size() > 0) {
            return true;
        }else{
            return false;
        }
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        throw new RuntimeException("Erro ao consultar existência de usuário com o documento solicitado");
    } finally {
        session.close();
    }
}
}

Authenticatable.java :

package br.com.diego.controle;

public interface Autenticavel {

public Autenticavel autenticar(String usuario, String senha);

public boolean existe(String usuario);
}

Testandohibernate.java :

package br.com.diego.modelo;

import br.com.diego.controle.Autenticavel;
import br.com.diego.controle.CPF;
import br.com.diego.controle.Cachorro;
import br.com.diego.controle.Consulta;
import br.com.diego.controle.DocReceita;
import br.com.diego.controle.Endereco;
import br.com.diego.controle.PF;
import br.com.diego.controle.Pet;
import br.com.diego.controle.Servico;
import br.com.diego.controle.Telefone;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import javax.swing.JOptionPane;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestandoHibernate {

public static void main(String[] args) throws Exception {

    GerarTabelas();

    if (autenticar("[email protected]", "root") != null) {
        System.out.println("Usuário autenticado");
    } else {
        System.out.println("Erro na autenticação");
    }
    try {
        persistindo();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Erro" + ex.getMessage());
    }
}

 public static Autenticavel autenticar(String usuario, String senha) {
    return new PF().autenticar(usuario, senha);
}

 private static void GerarTabelas() {
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    SchemaExport sx = new SchemaExport(cfg);
    sx.create(true, true);

}

private static void excluindo() {
}

 private static void persistindo() throws Exception {
    PF pf = new PF();
    pf.setNome("Diego");
    pf.setEmail("[email protected]");
    pf.setSenha("root");

    DocReceita CPF = new CPF(" 123. 359. 769-67 ");
    pf.setDocReceita(CPF);
    CPF.setCliente(pf);

    if (pf.existe(CPF) == true) {
        throw new RuntimeException("<br><center><font face='verdana' color='red'   size='2'><br />já existe usuário cadastrado com o CPF ou CNPJ informado</font></center><br>");
    }

    Endereco end = new Endereco();
    end.setBairro("Centro");
    end.setCep("28610180");
    end.setCidade("Nova Friburgo");
    end.setLograd("Pca Presidente Getulio Vargas");
    end.setNumero("203");
    end.setUf("RJ");
    end.setCliente(pf);

    Collection<Endereco> e = new ArrayList<Endereco>();
    e.add(end);
    pf.setEndereco(e);

    Telefone t = new Telefone();
    t.setCodArea(21);
    t.setNumero("983337760");
    t.setCliente(pf);

    Collection<Telefone> tel = new ArrayList<Telefone>();
    tel.add(t);
    pf.setTelefone(tel);

    Pet a = new Cachorro();
    Date d = new Date(2010, 4, 26);
    a.setDataNascimento(d);
    a.setNome("Rex");
    a.setRaca("Bulldog");
    a.setSexo('M');
    a.setObs("Peida muito!");
    a.setCliente(pf);

    Servico s = new Consulta();
    s.setData(new Date());
    s.setDescricao("Problema de peso");
    s.setValor(20);
    s.setPet(a);

    Collection<Servico> serv = new ArrayList<Servico>();
    serv.add(s);
    a.setServico(serv);

    Collection<Pet> peti = new ArrayList<Pet>();
    peti.add(a);
    pf.setPet(peti);

    PF.salvar(pf);
}    
}

Can someone help me? Thank you from now on!

  • What are the problems you are having? You could isolate them, so get better to solve?

  • In Discriminatorcolumn was set type, but was explicit to be a String? Take a look at the type of property that was created in the database for the type attribute.

  • 1

    @Denircarvalho my More problem is this: Hibernate: insert into Cliente (email, nome, senha, tipo) values (?, ?, ?, '1')&#xA;dez 16, 2015 8:34:55 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelperlogExceptions&#xA;WARN: SQL Error: 0, SQLState: S1009&#xA;dez 16, 2015 8:34:55 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelperlogExceptions&#xA;ERROR: Parameter index out of range (4 > number of parameters, which is 3).

  • @Douglasgaldino looks like this https://drive.google.com/open?id=0B8lZMvD1tbzRSkZuWVlsOEl5cE0

  • How’s the class save method PFMTD?

  • @Gustavocinque PF inherits the methods of Client, the class PF is like this, Class PF: package br.com.diego.controle;&#xA;&#xA;import javax.persistence.*;&#xA;&#xA;@Entity&#xA;@Inheritance(strategy = InheritanceType.JOINED)&#xA;@DiscriminatorValue("1")&#xA;public class PF extends Cliente {&#xA; &#xA; public PF(){&#xA; super.setTipo(PF);&#xA; }&#xA;}

Show 1 more comment

1 answer

0


Remove the attribute tipo in your class Cliente. The annotation @DiscriminatorColumn is enough.

If you need to specify a numeric field, add the attribute discriminatorType=DiscriminatorType.INTEGER in the annotation @DiscriminatorColumn.

Note: check also in your code that in some places you are opening transactions without giving commit or rollback. You really need a transaction to read the data?

  • Thank you for the help @utluiz but since you have two classes (PF and PJ) that inherit the methods and attributes of the Client class, the type attribute, can have value 1 or 2 to identify that among the child classes of Client 1 will be used for PF and 2 will be used for PJ. package br.com.diego.controle;&#xA;&#xA;import javax.persistence.*;&#xA;&#xA;@Entity&#xA;@Inheritance(strategy = InheritanceType.JOINED)&#xA;@DiscriminatorValue("1")&#xA;public class PF extends Cliente {&#xA; &#xA; public PF(){&#xA; super.setTipo(PF);&#xA; }&#xA;}

  • The type attribute is receiving the value 1, do not understand pq even fixed the value Hibernate still tries to pass type again according to the reported error Hibernate: insert into Cliente (email, nome, senha, tipo) values (?, ?, ?, '1') dez 16, 2015 8:34:55 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelperlogExceptions ERROR: Parameter index out of range (4 > number of parameters, which is 3)

  • @Diego I don’t think you understand, it’s not to remove the note, but the class attribute. I’m suspicious that Ibernate is trying to include the field twice because of this.

  • I couldn’t verify this information, but in all the examples I saw, the annotation contains the name of the discriminatory column, but nay has an attribute in the class with the same name, because you cannot under any circumstances modify this value. And the Hibernate that will control it through the instance of the classes.

  • Nailed it @utluiz thanks so much for the help!

  • I have a problem in system authentication, could help me in http://answall.com/questions/106695/erro-na-authenticat%C3%A7%C3%A3o-de-um-sistema-web

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.