Foreign key recording as null

Asked

Viewed 131 times

4

Foreign key is writing as null. I have done several searches I could not find a solution. Could help me find my error. This is an example that I searched on the internet, if I can popular the foreign key in the bank, I can do with the rest.

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>

I’d be very grateful if someone could help me....

  • Friend, try to change the order you save, as is the Estudante who has the Endereco, and not the other way around, Hibernate needs to have the Endereco first in the bank.

  • 1

    Thank you, that was it. manager.persist(address); student.setAddress(address); manager.persist(student);

1 answer

1


Hello, from what I saw in the comments you already managed to solve your problem, but another approach is to use the JPA so you don’t have to do this job of saving the Estudante then the Endereco, leaving it automatically (managed by JPA), so your code would look like this:

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

And finally in your controller it would be simpler, without the need to run save before, follow the code:

@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");
}

Browser other questions tagged

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