3

I am using the SQL objects API in the following lines of code in my data access object to get the name field from a row in an SQL table where the ID matches the one provided.

@SqlQuery("select name from users where id = :id")
String findNameById(@Bind("id") int id);

That works all well and good, but what on earth do I do if I want to return all of the fields for that row in the table, not just the name, but all colums for that record?

I did try using :

"select * from users where id = :id"

But that isn't right, it only seemed to return the id field (possibly as it is the first column in the table, and my method returns a string?)

Anyhow, I am all out of ideas on this and would appreciate all the help I can get.


Additional Info as I get requests for information :

This is the method signature of my method in the controller that calls my dao.

public String retrieveUserRecord(@PathParam("id") int id)

As you can see, it returns a string, as does the findNameByID method in the dao...

What I want to do, is pass the id using my method signature, and get back all of my columns as one nice JSON object if possible?

4

1 回答 1

4

当您想要获取所有字段时,返回类型不应该是字符串。我假设你有这样的“用户”模型。

  public class User {
     private Integer id;
     private String name;

    public User(id, name) {
      this.id = id;
      this.name = name;
   }
  }

有一些方法可以将 DB 结果映射到 Java 模型。您应该为类用户创建映射器。

 public class UserMapper<User>  implements ResultSetMapper<User> {
         public User map(int row, ResultSet rs, StatementContext ctx) throws SQLException { 
         return new User(rs.getInt("id"), rs.getString("name") );
         }
}

你应该在 sqlObject api 中提到这个映射器。

@SqlQuery("select * from users where id = :id")
@Mapper(UserMapper.class)
String retrieveUserRecord(@Bind("id") int id);

如果模型中有 setter 和 getter,也可以使用 MapResultAsBean。

你也可以使用这个库

于 2015-02-05T13:28:34.427 回答