Search code examples
javahibernatespring-mvcmybatisibatis

Persist object directly to db using mybatis


I am new to mybatis. Previously I used Hibernate ORM framework.Now I want to use mybatis for development.

Below is my mapper class where I can write the actual query for application.

public interface UserMapper {
  @Insert("INSERT into user(id,name,address) VALUES(#{uid}, #{uname}, #{uaddress})")
  void insertUser(User user);

    } 

I am getting the User information in request from front end application.

Below is my Controller::

@RequestMapping(value = "/userdetails", method = RequestMethod.POST, headers = "Accept=application/json")
    public @ResponseBody ResponseCodeModel userInfo(@RequestBody User user)
    {
        session.save(user);//In Hibernate

    }

If I used Hibernate I can directly persist the user object in db using session.save(userObject);

But in Mybatis ,I need to map all the user parameter in mapper query.

If my table having 50 coloumn then I need to mention all the parameter in query like below::

 public interface UserMapper {
      @Insert("INSERT into user(id,name,address,....50 Coloumn name) VALUES(#{uid}, #{uname}, #{uaddress} ,....50 model attribute name)")
      void insertUser(User user);      
        } 

Is there any easier way to persist the Model Object in DB using myBatis.


Solution

  • Mybatis is SQL Mapper, not ORM. then you indeed have to map.

    If you insert into all columns in the table then you may omit the columns name and specify values in right order, this is common SQL.