Question

I would like to write something like this in myBatis (using anotations instead of XML):

@Insert("INSERT INTO friendships (user_id, friend_id) VALUES (#{user.id}, {friend.id})")
public void insert(User user, User friend);

Is this possible? How exactly?

(Note, I would like to use Objects of type User for type-safty. I know that using int parameters and use #{1} and #{2} as placeholders would work)

Was it helpful?

Solution

You can use annotations to provide a namespace for multiple input parameters. These essentially give nice names to the #{1.foo} and #{2.bar} identifiers.

@Insert("INSERT INTO friendships (user_id, friend_id) VALUES (#{user.id}, 
#{friend.id})")
public void insert(@Param(value="user") User user, @Param(value="friend") User friend)

OTHER TIPS

It seems like this is not possible, so I created a wrapper class:

class Friendship {

  private final User user;
  private final User friend;

  public Friendship(User user, User friend) {
        this.user = user;
        this.friend = friend;
  }

  public int getUserId(){
        return user.getId();
  }

  public int getFriendId(){
        return friend.getId();
  }
}

And changed the Mapper to this:

@Insert("INSERT INTO friendships (user_id, friend_id) VALUES (#{userId}, #{friendId})")
public void insert(Friendship friendship);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top