开发者

How to add multiple named parameters to the SQL statement?

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 plac开发者_JS百科eholders would work)


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)


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜