4

Chave estrangeira está gravando como null. Tenho feito várias pesquisas não consegui achar uma solução. Poderiam me ajudar a achar meu erro. Esse é um exemplo que pesquisei na internet, se eu conseguir popular a chave estrangeira no banco, consigo fazer com o restante.

Student.java

        package com.servicos.model;         
        import javax.persistence.Column;
        import javax.persistence.Entity;
        import javax.persistence.GeneratedValue;
        import javax.persistence.Id;
        import javax.persistence.JoinColumn;
        import javax.persistence.OneToOne;
        import javax.persistence.Table;

        @Entity
        @Table(name = "STUDENT")
        public class Student {

            @Id
            @GeneratedValue
            @Column(name = "STUDENT_ID")
            private long id;

            @Column(name = "FIRST_NAME")
            private String firstName;

            @Column(name = "LAST_NAME")
            private String lastName;

            @Column(name = "SECTION")
            private String section;

            @OneToOne
            @JoinColumn(name="HOME_ADDRESS_ID")
            private Address address;


            public Student() {

            }

            public Student(String firstName, String lastName, String section) {
                this.firstName = firstName;
                this.lastName = lastName;
                this.section = section;
            }

            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 String getSection() {
                return section;
            }

            public void setSection(String section) {
                this.section = section;
            }

            public Address getAddress() {
                return address;
            }

            public void setAddress(Address address) {
                this.address = address;

            }

            @Override
            public String toString() {
                return "Student [id=" + id + ", firstName=" + firstName + ", lastName="
                        + lastName + ", section=" + section + ", address=" + address
                        + "]";
            }

        }

Address.java package com.servicos.model;

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

        @Entity
        @Table(name = "ADDRESS")
        public class Address {

            @Id @GeneratedValue
            @Column(name = "ADDRESS_ID")
            private long id;

            @Column(name = "STREET")
            private String street;

            @Column(name = "CITY")
            private String city;

            @Column(name = "COUNTRY")
            private String country;

            public Address() {

            }

            public Address(String street, String city, String country) {
                this.street = street;
                this.city = city;
                this.country = country;
            }

            public long getId() {
                return id;
            }

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

            public String getStreet() {
                return street;
            }

            public void setStreet(String street) {
                this.street = street;
            }

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getCountry() {
                return country;
            }

            public void setCountry(String country) {
                this.country = country;
            }

            @Override
            public String toString() {
                return "Address [id=" + id + ", street=" + street + ", city=" + city
                        + ", country=" + country + "]";
            }

        }

Home.java - Controller package com.servicos.controller;

        import org.hibernate.SessionFactory;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Controller;
        import org.springframework.transaction.annotation.EnableTransactionManagement;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.servlet.ModelAndView;
        import org.springframework.web.servlet.mvc.support.RedirectAttributes;

        import com.servicos.dao.ProgramasDao;
        import com.servicos.model.Address;
        import com.servicos.model.Student;

        @Controller
        @org.springframework.transaction.annotation.Transactional
        @EnableTransactionManagement
        @RequestMapping("/home")
        public class Home {

            @Autowired
            ProgramasDao programas = new ProgramasDao();


            @RequestMapping("/form")
            public ModelAndView form(Student student){
                ModelAndView modelAndView = new ModelAndView("/form");
                return modelAndView;
            }

                @RequestMapping(value="/save",method=RequestMethod.POST, name="saveEnd")
                public ModelAndView save(Student student, Address address, RedirectAttributes redirectAttributes){
                    programas.save(student);            
                    programas.saveAddress(address);
                    redirectAttributes.addFlashAttribute("sucesso","Artigo cadastrado com sucesso");
                    return new ModelAndView("redirect:/home/form");
                }
        }

form.jsp

        <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
            pageEncoding="ISO-8859-1"%>
            <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        </head>
        <body>


        <form:form servletRelativeAction="/home/save" cssClass="Student">
        <label>Nome</label>
        <input type="text" name="firstName" />
        <label>lastName</label>
        <input type="text" name="lastName" />
        <label>section</label>
        <input type="text" name="section" />
        <label>City</label>
        <input type="text" name="city" />
        <label>Country</label>
        <input type="text" name="country" />
        <label>Street</label>
        <input type="text" name="street" />

        <input type="submit" name="submit" />
        </form:form>
        </body>
        </html>

Ficarei muito grato se alguém puder me ajudar....

2
  • Amigo, tente mudar a ordem que você salva, como é o Estudante que tem o Endereco, e não o contrário, o hibernate precisa ter o registro do Endereco primeiro no banco. 14/10/2016 às 12:57
  • 1
    Obrigado, realmente era isso. manager.persist(address); student.setAddress(address); manager.persist(student);
    – debianx
    17/10/2016 às 13:13

1 Resposta 1

1

Olá, pelo que vi nos comentários você já conseguiu resolver seu problema, porem uma outra abordagem é usar o cascade do JPA para você não ter que realizar esse trabalho de salvar primeiro o Estudante depois o Endereco, deixando isso de forma automática(gerenciada pelo JPA), assim seu código ficaria da seguinte forma:

Address.java

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

@Entity
@Table(name = "ADDRESS")
public class Address {

    @Id @GeneratedValue
    @Column(name = "ADDRESS_ID")
    private long id;

    @Column(name = "STREET")
    private String street;

    @Column(name = "CITY")
    private String city;

    @Column(name = "COUNTRY")
    private String country;

    public Address() {

    }

    public Address(String street, String city, String country) {
        this.street = street;
        this.city = city;
        this.country = country;
    }

    public long getId() {
        return id;
    }

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

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "Address [id=" + id + ", street=" + street + ", city=" + city
                + ", country=" + country + "]";
    }

}

Student.java

import javax.persistence.*;

@Entity
@Table(name = "STUDENT")
public class Student {

    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    private long id;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "SECTION")
    private String section;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name="HOME_ADDRESS_ID")
    private Address address;


    public Student() {}

    public Student(String firstName, String lastName, String section) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.section = section;
    }

    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 String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;

    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName="
                + lastName + ", section=" + section + ", address=" + address
                + "]";
    }
}

E por fim no seu controller ficaria mais simples, sem a necessidade de executar o save antes, segue o código:

@RequestMapping(value="/save",method=RequestMethod.POST, name="saveEnd")
public ModelAndView save(Student student, Address address, RedirectAttributes redirectAttributes){
    student.setAddress(address);
    programas.save(student);
    redirectAttributes.addFlashAttribute("sucesso","Artigo cadastrado com sucesso");
    return new ModelAndView("redirect:/home/form");
}

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 .