1

I am new to MyBatis. I was searching for the solution of the following question throughout the day. Still can't find it.

So I have 2 tables in my Database

  1. instructor
  2. instructor_detail

Where there is a FK-PK relationship from instructor table to instructor_detail table.

My Instructor.java and InstructorDetail.java is as show below

public class Instructor {

    private int id;
    
    private String firstName;
    
    private String lastName;
    
    private String email;
    
    private InstructorDetail instructorDetail;
    
    //constructor,getters and setters
}

public class InstructorDetail {
    
    private int id;
    
    private String youtubeChannel;
    
    private String hobby;
   //constructor, getters and setters
}

So I instantiated an Instructor object as follows

InstructorDetail instructorDetail = new InstructorDetail("http://jishnu@youtube.com","Cricket");
Instructor instructor = new Instructor("Jishnu","M V","jishnu@outlook.com");
instructor.setInstructorDetail(instructorDetail);

I want to persist this instructor object in to my database table using MyBatis. How can I do that? If there is a way using XML and/or Annotation. Please help me with both/either of them.

Shadow
  • 33,525
  • 10
  • 51
  • 64
Jithin M V
  • 175
  • 1
  • 1
  • 10

1 Answers1

1

I want to persist this instructor object in to my database table using MyBatis

I presume you would like to insert two tables, instructor and instructor_details, after constructing this instructor object?

A little google, and here's an answered link describing inserting two tables in one call using mybatis.

In your case, XML would be fit. It would be something like this:

(I assumed your database has the convention of underscore "_", without quotes, as the separator)

<insert id="insertInstructorAndDetails">
   insert into instructor (id,first_name,last_name,email)
     values (#{id},#{firstname},#{lastName},#{email})
   insert into instructor_details (id, youtube_channel, hobby)
     values (#{id},#{instructorDetail.youtubeChannel},#{instructorDetail.hobby})
</insert>

Note that not all database support multiple insert statements.

  • Thank you for your answer. But the issue is not resolved yet. I know how to insert the independent values in to two tables in a go. But the issue here is that there is a FK in instructor table which refers to the instructor_detail table. The code provided by you is not inserting anything to that column in the instructor table. – Jithin M V Jan 04 '21 at 05:56