Mapmaneto Person x Document Onetoone, Cascade

Asked

Viewed 47 times

0

I created a Person class and a Document, the Document data I can make the persistence but when doing Onetoone in the Person class and insert a new table in the Person class appears an error that the Document_id table does not exist, which may have happened?

Person class

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 + "]";
    }

}

Document class

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);

    }

}

Main class

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 answers

0


Good afternoon friend. The mapping is unidirectional or bidirectional? To make the correct notes the decision about the mapping is fundamental.

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

The code fragment above shows that you are mapping a column called 'DOCUMENT_ID'. Is it in the PERSONS or DOCUMENTS table? Which of these tables is the dependent table?

  • Good afternoon Alexandre, this column DOCUMENT_ID should be created and appear in the Person table, because it will be included and will appear the attributes of the Person and Document classes. It is a Join operation that when I run Main the data will appear in the Person table along with the data from the Document table. In the Document table has an attribute Id with the name (ID_DOCUMENT)

  • Error: 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 (?, ?, ?, ?)

  • com.mysql.jdbc.exceptions.jdbc4.Mysqlsyntaxerrorexception: Unknown column 'DOCUMENT_ID' in 'field list'

  • Alexandre, I managed to solve my problem, I uninstalled my database that had been updated and installed a slightly older version and it worked perfectly my code and yours! Thank you so much for your help! The problem was updating the database...

0

Thiago, I will suggest another solution for you.

Database:

Tabela PERSON:

ID_PERSON
FIRST_NAME
LAST_NAME
AGE

Tabela DOCUMENTS:

ID_DOCUMENT
CPF
RG
PERSON_ID

The PERSON table, in my view, is the main table, and the DOCUMENTS table, the dependent table. So it would not make sense to have a table (DOCUMENTS), which only exists because of another (PERSON), not having a reference pointing to this table (PERSON).

Person class

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 + "]";
    }

}

Document class

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 + "]";
    }

}

Important: the person object must have a Document reference, and Document a person reference. The insertDocument method would look as follows:

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());

    }

So jpa/hiberrnate will know how to insert both person with document in the correct way.

I believe that this way you will be able to execute your queries of definition and queries.

  • Good evening Alexandre, thanks for your help. Now I managed to add the names but RG and CPF not. It appears that you entered but in fact you do not enter the ID and CPF. Hibernate: Insert into PERSONS (AGE, FIRST_NAME, LAST_NAME) values (?, ?) Hibernate: Insert into DOCUMENTS (CPF, PERSON_ID, RG) values (?, ?, ?) Exception in "main" javax.persistence.Persistencethread exception: org.hibernate.Exception.Sqlgrammarexception: could not execute statement com.mysql.jdbc.exceptions.jdbc4.Mysqlsyntaxerrorexception: Unknown column 'PERSON_ID' in 'field list'

  • Check whether in the database the PERSON_ID column was created in the DOCUMENTS table. If it does not exist, create this column and run a new test. The mysql error message refers to the absence of that column.

Browser other questions tagged

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