0

Eu criei uma classe Person e uma Document, os dados de Document eu consigo fazer a persistência mas na hora de fazer o OneToOne na classe Person e inserir uma nova tabela na classe Person aparece um erro que a tabela Document_ID não existe, o que pode ter acontecido?

Classe Person

package br.com.devmedia.revjpa.entity;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;


@Entity
@Table(name = "PERSONS",
        indexes = {@Index(columnList = "FIRST_NAME, LAST_NAME", name = "IDX_PERSON_NAME", unique = true)})

    public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID_PERSON")
    private Long id;

    @Column(name = "FIRST_NAME", nullable = false, length = 30)
    private String firstName;

    @Column(name = "LAST_NAME", nullable = false, length = 60)
    private String lastName;

    @Column(name = "AGE", nullable = false)
    private Integer age;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "DOCUMENT_ID")
    private Document document;



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }


    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.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;
        Person other = (Person) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age
                + ", document=" + document + "]";
    }

}

Classe Document

package br.com.devmedia.revjpa.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "DOCUMENTS")
public class Document implements Serializable {

    @Id
    @GeneratedValue(strategy  = GenerationType.IDENTITY)
    @Column(name = "ID_DOCUMENT")
    private Long id;

    @Column(name = "CPF", nullable = false, unique = true, length = 14)
    private String cpf;

    @Column(name = "RG", unique = true)
    private Integer rg;


    public Document() {
        super();
    }

    public Document(String cpf, Integer rg) {
        this.cpf = cpf;
        this.rg = rg;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public Integer getRg() {
        return rg;
    }

    public void setRg(Integer rg) {
        this.rg = rg;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.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;
        Document other = (Document) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Document [id=" + id + ", cpf=" + cpf + ", rg=" + rg + "]";
    }

}

DocumentDAO

package br.com.devmedia.revjpa.dao;

import br.com.devmedia.revjpa.entity.Document;

public class DocumentDAO extends GenericDAO<Document>{

    public DocumentDAO() {
        super(Document.class);

    }

}

Classe main

package br.com.devmedia.revjpa;


import java.util.List;

import br.com.devmedia.revjpa.dao.DocumentDAO;
import br.com.devmedia.revjpa.dao.PersonDAO;
import br.com.devmedia.revjpa.entity.Document;
import br.com.devmedia.revjpa.entity.Person;

public class AppRevJPA{ 

    public static void main( String[] args ) {
        System.out.println( "Hello World!" );

        //insertPerson();

        //métodos de relacionamento 1 x 1 entre as classes Person e Documents
        insertDocument();
        //updateDocument();

    }

    private static void insertDocument() {

        Person p1 = new Person();
        p1.setFirstName("Jão");
        p1.setLastName("de Souza");
        p1.setAge(24);
        p1.setDocument(new Document("123.456.789-44", 111111115));

        new PersonDAO().save(p1);

        System.out.println(p1.toString());

    }

    private static void deletePerson() {
        new PersonDAO().delete(3L);

    }

    private static void updatePerson() {
        Person p1 = new PersonDAO().findById(3L);

        System.out.println(p1.toString());

        p1.setLastName("de Souza");

        new PersonDAO().update(p1);

        Person p2  = new PersonDAO().findById(3L);

        System.out.println(p2.toString());

    }


    private static void findByFullName() {
        Person person = new PersonDAO().findByFullName("Bruna", "Figueira");

        System.out.println(person.toString());
    }


    private static void findByAge() {
        List<Person> persons = new PersonDAO().findAgeIsBetween(27, 36);

        for (Person person : persons) {
            System.out.println(person.toString());      
        }
    }


    private static void findByLastName() {
        List<Person> persons = new PersonDAO().findByLastName("Figueira");

        for (Person person : persons) {
            System.out.println(person.toString());      
        }
    }


    private static void countPersons() {
        long total = new PersonDAO().count();

        System.out.println("Total de Pessoas: " + total);
    }


    private static void findAllPersons() {
        List<Person> persons = new PersonDAO().findAll();

        for(Person p : persons) {
            System.out.println(p.toString());
        }   
    }


    private static void findPersonById() {
        Person p1 = new PersonDAO().findById(2L);

        Person p2 = new PersonDAO().findById(4L);

        System.out.println(p1.toString());
        System.out.println(p2.toString());

    }


    private static void insertPerson() {
        Person p1 = new Person();
        p1.setFirstName("Fabiana");
        p1.setLastName("da Silva");
        p1.setAge(29);
        new PersonDAO().save(p1);

        System.out.println(p1.toString());

        Person p2 = new Person();
        p2.setFirstName("Gilberto");
        p2.setLastName("Figueira");
        p2.setAge(36);
        new PersonDAO().save(p2);

        System.out.println(p2.toString());

        Person p3 = new Person();
        p3.setFirstName("Carlos Andre");
        p3.setLastName("Rodrigues");
        p3.setAge(36);
        new PersonDAO().save(p3);

        System.out.println(p3.toString());
    }
}

2 Respostas 2

0

Boa tarde amigo. O mapeamento é unidirecional ou bidirecional? Para fazer as anotações corretas a decisão sobre o mapeamento é fundamental.

@OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "DOCUMENT_ID") private Document document;

O fragmento de código acima mostra que você está mapeando uma coluna chamada 'DOCUMENT_ID'. Ela está na tabela PERSONS ou DOCUMENTS? Qual dessas tabelas é a tabela dependente?

4
  • Boa tarde Alexandre, essa coluna DOCUMENT_ID deveria ser criada e aparecer na tabela Person, por que ela será incluída e aparecerá os atributos das classe Person e Document. Ela é uma operação Join que quando eu rodar o Main aparecerão os dados na tabela Person junto com os dados da tabela Document. Na tabela Document tem um atributo Id com o nome (ID_DOCUMENT) 25/02/2018 às 20:48
  • Erro: Hibernate: alter table PHONES add constraint FKa85nuf9cg6ckeuirthj9u7x78 foreign key (PERSON_ID) references PERSONS (ID_PERSON) Hibernate: insert into DOCUMENTS (CPF, RG) values (?, ?) Hibernate: insert into PERSONS (AGE, DOCUMENT_ID, FIRST_NAME, LAST_NAME) values (?, ?, ?, ?) 25/02/2018 às 20:50
  • com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'DOCUMENT_ID' in 'field list' 25/02/2018 às 20:50
  • Alexandre, eu consegui resolver meu problema, eu desinstalei o meu banco de dados que havia sido atualizado e instalei uma versão um pouco mais antiga e funcionou perfeitamente o meu código e o seu! Muito obrigado pela ajuda! O problema era a atualização do banco de dados... 1/03/2018 às 1:19
0

Thiago, vou sugerir uma outra solução para você.

Banco de dados:

Tabela PERSON:

ID_PERSON
FIRST_NAME
LAST_NAME
AGE

Tabela DOCUMENTS:

ID_DOCUMENT
CPF
RG
PERSON_ID

A tabela PERSON, a meu ver, é a tabela principal, e a tabela DOCUMENTS, a tabela dependente. Então não faria sentido uma tabela(DOCUMENTS), que só existe em função de outra(PERSON), não ter uma referência apontando para essa tabela(PERSON).

Classe Person

package br.com.devmedia.revjpa.entity;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "PERSONS",
        indexes = {@Index(columnList = "FIRST_NAME, LAST_NAME", name = "IDX_PERSON_NAME", unique = true)})

    public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID_PERSON")
    private Long id;

    @Column(name = "FIRST_NAME", nullable = false, length = 30)
    private String firstName;

    @Column(name = "LAST_NAME", nullable = false, length = 60)
    private String lastName;

    @Column(name = "AGE", nullable = false)
    private Integer age;

    @OneToOne(mappedBy="person", cascade = CascadeType.ALL)
    private Document document;



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }


    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person= person;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.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;
        Person other = (Person) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age
                + ", document=" + document + "]";
    }

}

Classe Document

package br.com.devmedia.revjpa.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "DOCUMENTS")
public class Document implements Serializable {

    @Id
    @GeneratedValue(strategy  = GenerationType.IDENTITY)
    @Column(name = "ID_DOCUMENT")
    private Long id;

    @Column(name = "CPF", nullable = false, unique = true, length = 14)
    private String cpf;

    @Column(name = "RG", unique = true)
    private Integer rg;

    @OneToOne
    @JoinColumn(name="PERSON_ID")
    private Person person;


    public Document() {
        super();
    }

    public Document(String cpf, Integer rg) {
        this.cpf = cpf;
        this.rg = rg;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public Integer getRg() {
        return rg;
    }

    public void setRg(Integer rg) {
        this.rg = rg;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.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;
        Document other = (Document) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Document [id=" + id + ", cpf=" + cpf + ", rg=" + rg + "]";
    }

}

Importante: o objeto person deve ter uma referência para document, e document uma referência para person. O método insertDocument ficaria da seguinte forma:

private static void insertDocument() {

        Person p1 = new Person();
        p1.setFirstName("Jão");
        p1.setLastName("de Souza");
        p1.setAge(24);

        Document d1 = new Document("123.456.789-44", 111111115);

        d1.setPerson(p1);
        p1.setDocument(d1);

        new PersonDAO().save(p1);

        System.out.println(p1.toString());

    }

Assim o jpa/hiberrnate saberá inserir tanto pessoa com documento da forma correta.

Acredito que dessa forma você conseguirá executar suas queries de definição e de consultas.

2
  • Boa noite Alexandre, desde já obrigado pela ajuda. Agora eu consegui adicionar os nomes mas o RG e CPF não. Aparece que inseriu mas na verdade não insere o RG e CPF. Hibernate: insert into PERSONS (AGE, FIRST_NAME, LAST_NAME) values (?, ?, ?) Hibernate: insert into DOCUMENTS (CPF, PERSON_ID, RG) values (?, ?, ?) Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'PERSON_ID' in 'field list' 26/02/2018 às 1:23
  • Verifica, se no banco de dados, a coluna PERSON_ID foi criada, na tabela DOCUMENTS. Se ela não existir, crie essa coluna e faça um novo teste. A mensagem de erro do mysql se refere à inexistencia dessa coluna. 26/02/2018 às 2:06

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .