Problem to recover data using Hibernate

Asked

Viewed 65 times

1

I can list the Customer and their Animals, but I can’t list the Animal Breeds.

Follows the involved relationship classes:

Client class

@Entity
public class Cliente extends Pessoa {

@Column(name="forma_pagamento", length=20, nullable=false)
private String formaPagamento;

@OneToMany(mappedBy="cliente", cascade=CascadeType.PERSIST)
private List<Animal> animais;

public String getFormaPagamento() {
    return formaPagamento;
}

public void setFormaPagamento(String formaPagamento) {
    this.formaPagamento = formaPagamento;
}

public List<Animal> getAnimais() {
    return animais;
}

public void setAnimais(List<Animal> animais) {
    this.animais = animais;
}

}

Animal Class

@Entity
public class Animal {

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ID_ANIMAL")
@SequenceGenerator(name="ID_ANIMAL", sequenceName="SEQ_ID_ANIMAL", initialValue=1 ,allocationSize=1)
private int id;

@Column(length=25, nullable=false)
private String nome;

private int idade;

@Column(nullable=false)
private char sexo;

@ManyToOne
@JoinColumn(name="id_cliente")
private Cliente cliente;

@ManyToOne
@JoinColumn(name="raca")
private Raca raca;

public int getId() {
    return id;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public int getIdade() {
    return idade;
}

public void setIdade(int idade) {
    this.idade = idade;
}

public char getSexo() {
    return sexo;
}

public void setSexo(char sexo) {
    this.sexo = sexo;
}

public Cliente getCliente() {
    return cliente;
}

public void setCliente(Cliente cliente) {
    this.cliente = cliente;
}

public Raca getRaca() {
    return raca;
}

public void setRaca(Raca raca) {
    this.raca = raca;
}

}

Classe Raça

@Entity
public class Raca {

@Id
private String nome;

@OneToMany(mappedBy="raca")
private List<Animal> animais;

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public List<Animal> getAnimais() {
    return animais;
}

public void setAnimais(List<Animal> animais) {
    this.animais = animais;
}

}

inserir a descrição da imagem aqui

Problem solved, I just overwrote the method toString class Raca and I decided.

  • 1

    You need to implement toString in the Raca class, otherwise the Java behavior is the same: use the hash in toString

  • Aha, I forgot that... I made it only Person class, but not Race class.

1 answer

0

Hello,

with the animal instance you only had access to the race object, in order to be able to access the attribute "Breed class name" just add the getName() as below:

animal.getRaca(). getName();

  • So, I just overwrote the toString method and managed to return the name of the breed.

Browser other questions tagged

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