0

I have 2 tables, Table 1 has a ID column which is auto generated. I have this Id as a foreign key with table 2, I am using mybatis to insert data into tables. I am stuck at point where I need to send the foreign key to insert command dynamically.

Table 1

CLM_ID (PK) AUTO GENERATED
CLM_VALUE NN UNIQUE

TABLE 2

CLM_ID (FK) 
CML_VALUE1 (NN)
CML_VALUE2 (NN)
CML_VALUE3 (NN)

Upon request I am storing the data into table 1 where ID is generated automatically. when I am trying to store the data in table 2 how do I get the {ID}

If I know the value of the corresponding column I can get the ID associated with that column. But how do I pass the column name dynamically.

Sample Mapper example I have.

public class Address {

    private Integer address_ID; //PK auto generated
    private String name;
    // getters and setters
}
public class Home {

    private Integer addressID; //FK
    private String Name;
}

public interface HomeMapper {

    String INSERT_ADDRESS = "INSERT INTO HOMES(ADDRESS_ID, NAME) VALUES ( {addressID}, #{name})";

    @Insert(INSERT_ADDRESS)
    @SelectKey(**statement="SELECT ADDRESS_ID FROM ADDRESSES WHERE NAME='Mintu'**", keyProperty = "addressID", before=true, resultType=int.class)
    public void insertRecord(Home homeName);

}

How do I send the values dynamically to statement?

Can someone help me to handle this situation? I am new to mybatis and not sure if this is the way to achieve this.

demongolem
  • 9,474
  • 36
  • 90
  • 105
  • pls check [this](http://stackoverflow.com/questions/18507508/mybatis-how-to-get-the-auto-generated-key-of-an-insert-mysql) for how to get back autogenerated key in MyBatis – Marmite Bomber Mar 07 '17 at 18:09
  • Thanks this helps to get the auto generated keys but if I want to insert it back into the different table having different mapper how do we do that. – Mintu reddy Mar 07 '17 at 19:37
  • You generate key before insert, this is same scenario as [here](http://stackoverflow.com/a/30027349/7076047) with sequence. The generated key is written back in the _keyProperty_ of the parameter then you can reuse it for further statement. And by the way, your Home class would better have an Address type property then accessed `#{address.address_id}` – blackwizard Mar 08 '17 at 16:39

0 Answers0