0

I created a Spring Boot project for One to One mapping by using H2 database, when i created a record the foreign key in other table is showing null.

Db related set up and console is fine, when i am seeing the records, then i found the null value.

Pls guide where i am doing the mistake.

I tried with out One to One join, it is working fine.

Schema.sql


DROP TABLE IF EXISTS instructor;

CREATE TABLE instructor (
  id INT AUTO_INCREMENT  PRIMARY KEY,
  first_name VARCHAR(250) NOT NULL,
  last_name VARCHAR(250) NOT NULL,
  email VARCHAR(250) DEFAULT NULL
);


DROP TABLE IF EXISTS instructor_detail;

CREATE TABLE instructor_detail (
    id INT AUTO_INCREMENT PRIMARY KEY,
    instructor_id INT,
    youtube_channel VARCHAR(250) NOT NULL,
    hobby VARCHAR(20) NOT NULL,
    FOREIGN KEY (instructor_id) REFERENCES instructor(id)
);

Instructor.java


@Table(name = "instructor")
public class Instructor {

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

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

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

    @Column(name = "email")
    private String email;

    @OneToOne(cascade = CascadeType.ALL,mappedBy="instructor")
    private InstructorDetail instructorDetail;

    public Instructor(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
}

InstructorDetail.java


@Table(name = "instructor_detail")
public class InstructorDetail {

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

    @Column(name = "youtube_channel")
    private String youtubeChannel;

    @Column(name = "hobby")
    private String hobby;

    @OneToOne
    @JoinColumn(name = "instructor_id", nullable = false)
    private Instructor instructor;

    public InstructorDetail(String youtubeChannel, String hobby) {
        this.youtubeChannel = youtubeChannel;
        this.hobby = hobby;
    }
}

Main Java Class


@SpringBootApplication
public class H2JoinExampleApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(H2JoinExampleApplication.class, args);
    }

    @Autowired
    private InstructorRepository instructorRepository;

    @Override
    public void run(String...args) throws Exception {

        Instructor instructor = new Instructor("ABC", "EFG", "ABC@gmail.com");

        InstructorDetail instructorDetail = new InstructorDetail("Java", "Cricket");

        // associate the objects
        instructor.setInstructorDetail(instructorDetail);

        instructorRepository.save(instructor);
    }
}
mohan
  • 447
  • 4
  • 11
  • 26

0 Answers0