问题
I am new to spring world, in above code i understand query but i don't get why "new MapSqlParameterSource("username" ,username)" is used?
public boolean exists(String username) {
return jdbc.queryForObject("select count(*) from users where username=:username",
new MapSqlParameterSource("username" ,username),Integer.class)>0; }
what is the purpose of using it?
Thanks in advance
回答1:
It is because some developers do not like use ?
in a sql sentence.
This ?
is named or referred how (mostly the first):
- Placeholders
- Bind parameter
Therefore Spring offers the same approach, it such as how Hibernate/JPA does with :parameter
, it through the MapSqlParameterSource
class.
I suggest you do a research about RowMapper<T>
too.
回答2:
If you have a Map representing data - especially from non-db sources (a file, an ldap query) - you can use a map as your model of that data.
List of Users
List<Map<String, Object>> users = new ArrayList<Map<String, Object>>(25);
Example Map entry - likely from iterating over a file, or some other data source:
Map<String, Object> user1 = new HashMap<String, Object>();
user1.put("cn", "user1");
user1.put("mail", "user1@example.com");
Map<String, Object> user2 = new HashMap<String, Object>();
user2.put("cn", "user2");
user2.put("mail", "user2@example.com");
Now NamedJdbcTemplate can easily set your sql bind values - I find it particular useful when batching a lot of data to the database from non-db data-sources that I'll use a Map as the data structure.
SqlParameterSource[] batch = new SqlParameterSource[nyssisUsers.size()];
users.eachWithIndex { ldapEntry, index ->
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(ldapEntry);
batch[index] = mapSqlParameterSource
}
namedParameterJdbcTemplate.batchUpdate(SAVE_USER_SQL, batch);
Summary: Using a Map as a data structure to represent a line in a file, another database source, a one-time ETL operation, a read from an LDAP etc... is very useful. Since the Map already has keys it makes sense to want to use those keys in your SQL template. For the example above that can in turn be a simple insert, merge or update sql statement or an anonymous block of pl/sql code. Whatever the need is that you are addressing.
SAVE_USER_SQL could be as involved as:
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;
'''
来源:https://stackoverflow.com/questions/24742116/why-we-use-mapsqlparametersource