2014-07-14 113 views
1

我是新来的春天,在上面的代码我明白查询,但我不明白为什么 “新的MapSqlParameterSource(”用户名“,用户名)”?为什么我们使用MapSqlParameterSource

public boolean exists(String username) {  
     return jdbc.queryForObject("select count(*) from users where username=:username", 
      new MapSqlParameterSource("username" ,username),Integer.class)>0;          } 

使用它的目的是什么?

在此先感谢

+0

考虑我怎么回答正确,你能标记检查? –

回答

2

这是因为一些开发商不喜欢使用“?”在一个SQL语句,因此Spring提供了同样的做法,休眠/ JPA与怎么做:参数,通过MapSqlParameterSource

我建议你做一个研究关于的RowMapper了。

0

如果你有代表数据的地图 - 特别是来自非数据库源(文件,LDAP查询) - 您可以使用地图为您的数据的模型。用户的

列表

List<Map<String, Object>> users = new ArrayList<Map<String, Object>>(25); 

实例映射条目 - 可能来自遍历文件,或一些其他数据源:

Map<String, Object> user1 = new HashMap<String, Object>(); 
user1.put("cn", "user1"); 
user1.put("mail", "[email protected]"); 
Map<String, Object> user2 = new HashMap<String, Object>(); 
user2.put("cn", "user2"); 
user2.put("mail", "[email protected]"); 

现在NamedJdbcTemplate可以轻松地设置您的SQL绑定值 - 我发现它特别有用,当批处理大量的数据从非db数据库的数据源,我将使用映射为数据结构。

SqlParameterSource[] batch = new SqlParameterSource[nyssisUsers.size()]; 
users.eachWithIndex { ldapEntry, index -> 
    MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(ldapEntry); 
    batch[index] = mapSqlParameterSource 
} 
namedParameterJdbcTemplate.batchUpdate(SAVE_USER_SQL, batch); 

总结: 使用地图作为数据结构来表示在文件中的线,另一个数据库源,一次性ETL操作,从LDAP等的读出......是非常有用的。由于Map已经有了键,所以想要在SQL模板中使用这些键是有意义的。对于上面的例子,这可以反过来是一个简单的插入,合并或更新SQL语句或一个匿名的PL/SQL代码块。无论你需要什么,你正在处理。

SAVE_USER_SQL可能是因为参与为:

private static final String SAVE_USER_SQL = ''' 
DECLARE 
    P_CN     VARCHAR2 (100); 
    P_MAIL     VARCHAR2 (75); 
    P_GIVENNAME   VARCHAR2 (255); 
    P_SN     VARCHAR2 (255); 
    P_TITLE    VARCHAR2 (75); 
    P_O     VARCHAR2 (75); 
BEGIN 
    P_CN := trim(lower(:cn)); 
    P_MAIL := trim(lower(:mail)); 
    P_GIVENNAME := initCap(:givenName); 
    P_SN := initCap(:sn); 
    P_TITLE := upperCase(:title); 
    P_O := upperCase(:o); 

    USERS_PKG.SAVE (P_CN, 
        P_MAIL, 
        P_GIVENNAME, 
        P_SN, 
        P_TITLE, 
        P_O); 
END; 
''' 
相关问题