English 中文(简体)
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 placeholders 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);




相关问题
Hibernate Vs iBATIS [closed]

For our new product re-engineering, we are in the process of selecting the best framework from Java. As the consideration is to go for database agnostic approach for model, we are working on options ...

ibatis java.util.Map parameters with dot(.) character

I have a parameters Map with property name "xx.xx", but Ibatis cannot know property named "xx.xx" ("xxxx" is ok). how can I use Map property with name contains dot(.) character? or I have to remove ...

MySQL like query runs extremly slow for 5000 records table

I have this issue on our production server. The application stack is, Java Web App on Tomcat 6.0.18 iBatis data access layer MySQL 5.0 database CentOS The system is deployed on virtual server having ...

Hibernate or iBatis or something else?

In my project i need to switch between databases during runtime. I tried to use Hibernate, but stuck in a place, where i need to map object with table in database. The problem is, that i have several ...

Hibernate vs Ibatis caching

We can speed up a hibernate app easyly with 2nd level cache using infinispan or ehcache/terracotta,... but ibatis only have a simple interface to implement for caching. And hibernate knows more ...

热门标签