Problem to save with Hibernate, verified type is different from expected

Asked

Viewed 117 times

0

I’m having a problem saving two tables (@OneToOne) in the bank using Hibernate. Using weak relationship entities (person, address).

Errors shown on console:

Initial Sessionfactory Creation failed.org.Hibernate.Hibernateexception: Wrong column type in public.Citizen for column neighborhood_id. Found: int4, expected: bytea Exception in thread "main" java.lang.Exceptionininitializererror at zup.model.utils.HibernateUtil.(Hibernateutil.java:29) at zup.business.Abstractbusiness.save(Abstractbusiness.java:25) at zup.business.Citizenbusiness.main(Citizenbusiness.java:131) Caused by: org.hibernate.Hibernateexception: Wrong column type in public.Citizen for column neighborhood_id. Found: int4, expected: bytea at org.hibernate.Mapping.Table.validateColumns(Table.java:372) at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1338) at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(Schemavalidator.java:175) at org.hibernate.Internal.SessionFactoryImpl.(Sessionfactoryimpl.java:525) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859) at zup.model.utils.HibernateUtil. (Hibernateutil.java:25)

To my model class:

//pacote

//importações

//named queries

public class Citizen implements Serializable/*, Comparable<MessageModel>*/{
    private static final long serialVersionUID = 1L;

    @Id
    @Size(min = 11, max = 11)
    @Column(name = "citizen_cpf")
    private String citizen_cpf;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Size(min=3, max = 40, message = IMessages.SIZE_LIMIT_EXCEEDS)//detalhar o min�mo depois quando for tratar a inclus�o
    @Column(name = "name")
    private String name;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Size(min = 11, max = 11)
    @Column(name = "phone_number")
    private String phone_number;


    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Column(name = "email")
    private String email;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Size(min = 1, max = 30)
    @Column(name = "city_name")
    private String city_name;


    //////////////////////////////////////////////////////////////////////////////
    //@OneToOne
    //@PrimaryKeyJoinColumn
    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Column(name = "neighborhood_id")
    private Neighborhood neighborhood;

    @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="neighborhood_id")//chamando nesse atributo so valores da coluna neighborhood_id de outra tabela
    public Neighborhood getNeighborhood() {
        return neighborhood;
    }

    public Neighborhood setNeighborhood(Neighborhood n) {
        this.neighborhood = n;
        return neighborhood;
    }
    //////////////////////////////////////////////////////////////////////////////


    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Size(min = 1, max = 100)
    @Column(name = "street_name")
    private String street_name;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Column(name = "address_number")
    private int address_number;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Column(name = "home_address_geograpical_coordinates")
    private String home_address_geograpical_coordinates;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Column(name = "photo")
    private byte[] photo;

    public Citizen() {
    }

    //o construtor que eu estou utilizando para gerar meu objeto
    public Citizen(String city_name, String home_address_geograpical_coordinates, String citizen_cpf, String name, byte[] photo, String phone_number, String email, String street_name, int address_number) {
        this.citizen_cpf = citizen_cpf;
        this.name = name;
        this.phone_number = phone_number;
        this.email = email;
        this.city_name = city_name;
        this.street_name = street_name;
        this.address_number = address_number;
        this.home_address_geograpical_coordinates = home_address_geograpical_coordinates;
        this.photo = photo;
    }
    //metodos privados
    //aqui ficaria todos os setters and getters

    //métodos sobrescritos
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (citizen_cpf != null ? citizen_cpf.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Citizen)) {
            return false;
        }
        Citizen other = (Citizen) object;
        if ((this.citizen_cpf == null && other.citizen_cpf != null) || (this.citizen_cpf != null && !this.citizen_cpf.equals(other.citizen_cpf))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "banco.Citizen[ CitizenId=" + citizen_cpf + " ]";
    } 
}

The second class that will set the values as foreign key in the above-mentioned class:

package zup.bean;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlRootElement;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

import zup.messages.IMessages;

@Entity
@Table(name = "neighborhood")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Neighborhood.findAll", query = "SELECT c FROM Neighborhood c ORDER BY c.neighborhood_name"),
    //@NamedQuery(name = "Neighborhood.findByNeighborhoodId", query = "SELECT c FROM Neighborhood c WHERE c.NeighborhoodCPF = :NeighborhoodCPF"),
    @NamedQuery(name = "Neighborhood.findByName", query = "SELECT c FROM Neighborhood c WHERE c.neighborhood_name = :neighborhood_name")})

public class Neighborhood implements Serializable{

private static final long serialVersionUID = 1L;

    //-------------------------------------------------------------------------------
    //vari�veis e suas especifica��es
    @Id
    //@OneToOne( mappedBy="neighborhood_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "neighborhood_id")
    private int neighborhood_id;

    @NotEmpty(message = IMessages.NULL_FIELDS)
    @Size(min=3, max=60)//lembrando que nas especifica��es at� agora o m�nimo ainda n�o foi estipulado
    @Column(name = "neighborhood_name")//por conven��o estou colocando o valor que repassaram para o front-end
    private String neighborhood_name;

    //--------------------------------------------------------------------------------
    //metodos privados
    public String getNeighborhood_name() {
        return neighborhood_name;
    }

    public void setNeighborhood_name(String name) {
        this.neighborhood_name = name;
    }

    public int getNeighborhood_id() {
        return neighborhood_id;
    }

    //---------------------------------------------------------------------------------
    //construtores
    public Neighborhood(){
    }

    public Neighborhood(String name){//lembrando esse construtor recebe apenas o nome porque o id � auto incrementado
        this.neighborhood_name = name;
    }
}

And the test part I’m using to test my bank inserts:

public static void main(String[] args) throws HibernateException, SQLException {

    Neighborhood n = new Neighborhood("Carajás");
    String data = "ainda sem caminho para a foto";
    byte[] photo = data.getBytes();
    NeighborhoodBusiness nb = new NeighborhoodBusiness();
    nb.save(n);

    Citizen s = new Citizen();
    s.setNeighborhood(n);
    //int a = s.getNeighborhood().getNeighborhood_id();
    //System.out.println(a);
    //System.out.println("*-----------------------------*");
    Citizen c = new Citizen("Patrocínio", "b", "12345678912", "Rafael", photo, "34383156899", "[email protected]",  "Avenida Brasil", 611);
    //Citizen c = new Citizen("12345678912", "Rafael", "34383156899", "[email protected]", "Patrocínio", "Avenida Brasil", 611, "b", photo);

    CitizenBusiness cb = new CitizenBusiness();
    cb.save(c);
    System.out.println(cb.findByCPF("12345678912").getcitizen_cpf());
    System.out.println(cb.findByEmail("[email protected]").get(0).getEmail());
    //System.out.println(cb.findBy("12345678912").getCitizenCPF());
    System.out.println(cb.findByName("Rafael").get(0).getName());
    //System.out.println(cb.findByCPF("12345678912").getCitizenCPF());  

}
  • Post the code you’re doing to save

  • Basically the mistake says I expected byte and received int

  • I will place in stages and simplify some pieces that are not relevant

  • Pass the notes that are on neighborhood for getNeighborhood(), or vice versa. This error is because neighborhood is being serialized and as it is binary there is no way to persist in integer type. You should remove @Column of neighborhood also, she is not using in relationships.

No answers

Browser other questions tagged

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