Search code examples
javamysqlmybatisspring-mybatis

How to save a JavaBean contains list to Sql By using Mybatis?


As we all know, when using Hibernate, it can create sql tables for us. Even a Java Bean has a list, hibernate will create a foreign table for us.

However, when I use myBatis, I find it very inconvenient that I have to create the table by myself ahead. Then I can insert values to the table. What is more inconvenient and I am not sure is that when I have a JavaBean with a list, I want to save this document to mysql.

For example, My java bean:

public class Person {
    public String id;
    public List<String> interests;
}

Then, Mysql should have a primary table (person table) and a foreign table (interests table).

My question is: 1. Can mybatis create these two tables for me? 2. Can mybatis auto convert the javabean for me and insert values to both two tables. For instance (of course this is not correct)

<insert id="insertPerson">
    INSERT INTO Person.java TO Database
</insert>

Solution

    1. No, you do not want it. Do not use MyBatis in the same way as Spring Data or Hibernate.
    2. About auto conversion. You should provide mapping for all related types (PersonInterest in our condition). Handle correct insertion on your Service layer. Selection could be provided by MyBatis with @Many(select = "selectPersonInterests")

      @Mapper
      public interface PersonMapper {
      
          @InsertProvider(type = PersonProvider.class, method = "insertPerson")
          void insertPerson(@Param("person") Person person);
      
          @InsertProvider(type = PersonProvider.class, method = "insertPersonInterest")
          void insertInterestItem(@Param("interest") Interest item);
      }
      
      @Component
      public class PersonProvider {
          public String insertPersonInterest() {
              return  "insert into person_interest (...) " +
                      "values (#{...}, ...);";
          }
          public String insertPerson() {
              return  "insert into person (...) " +
                      "values (#{...}, ...);";
          }
      }