回答編集履歴
1
2種類のJdbcTemplateの記述に変更。
answer
CHANGED
@@ -1,5 +1,4 @@
|
|
1
|
-
JdbcTemplateのqueryForObjectを使う場合のパラメータ指定
|
1
|
+
JdbcTemplateのqueryForObjectを使う場合のパラメータ指定ですが、利用するJdbcTemplateで、いわゆるPreparedStatement(?で指定する方法)のSQLを使うか、変数を指定するプレースホルダにする NamedParameterJdbcTemplate を使う方法(id = :id で指定する方法)があります。
|
2
|
-
(id = :id で指定する方法は、また別です)
|
3
2
|
|
4
3
|
例えば、以下で定義されるテーブルで
|
5
4
|
|
@@ -7,9 +6,14 @@
|
|
7
6
|
CREATE TABLE account (id INT, name VARCHAR(256))
|
8
7
|
```
|
9
8
|
|
10
|
-
このテーブルに対して、id を指定して検索するSQL
|
9
|
+
このテーブルに対して、id を指定して検索するSQLを、NamedParameterJdbcTemplate ならば
|
11
10
|
|
12
11
|
```sql
|
12
|
+
SELECT id, name FROM account WHERE id = :id
|
13
|
+
```
|
14
|
+
素のJdbcTemplateは、
|
15
|
+
|
16
|
+
```sql
|
13
17
|
SELECT id, name FROM account WHERE id=?
|
14
18
|
```
|
15
19
|
|
@@ -23,16 +27,49 @@
|
|
23
27
|
}
|
24
28
|
```
|
25
29
|
|
26
|
-
これを実行する処理は
|
30
|
+
これを実行する処理は、お使いのJdbcTemplateによりパラメータの格納方法が異なります。
|
31
|
+
NamedQuery~の方がパラメータの格納がしやすく(※)、視認性もとても高いので、ご希望されているNamedQuery~が良いですね!
|
27
32
|
|
33
|
+
※SqlParameterSource param = new MapSqlParameterSource().addValue("id", id); や Beanを丸ごと定義できる BeanPropertySqlParameterSource(..) が使えます。
|
34
|
+
|
35
|
+
NamedParameterJdbcTemplate :
|
36
|
+
|
28
37
|
```java
|
29
38
|
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
39
|
+
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
40
|
+
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
41
|
+
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
42
|
+
import org.springframework.stereotype.Repository;
|
43
|
+
|
44
|
+
import lombok.RequiredArgsConstructor;
|
45
|
+
|
46
|
+
@Repository
|
47
|
+
@RequiredArgsConstructor
|
48
|
+
public class NamedQueryAccountRepository {
|
49
|
+
private final NamedParameterJdbcTemplate template;
|
50
|
+
|
51
|
+
public Account findById(Integer id) {
|
52
|
+
SqlParameterSource param = new MapSqlParameterSource().addValue("id", id);
|
53
|
+
return template.queryForObject("SELECT id, name FROM account WHERE id = :id", param, new BeanPropertyRowMapper<Account>(Account.class));
|
54
|
+
}
|
55
|
+
```
|
56
|
+
|
57
|
+
素のJdbcTemplate :
|
58
|
+
```java
|
59
|
+
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
30
60
|
import org.springframework.jdbc.core.JdbcTemplate;
|
31
61
|
import org.springframework.stereotype.Repository;
|
32
62
|
|
63
|
+
import lombok.RequiredArgsConstructor;
|
64
|
+
|
65
|
+
@Repository
|
66
|
+
@RequiredArgsConstructor
|
67
|
+
public class AccountRepository {
|
68
|
+
private final JdbcTemplate jdbcTemplate;
|
33
69
|
public Account findById(int id) {
|
34
70
|
return jdbcTemplate.queryForObject("SELECT id, name FROM account WHERE id=?"
|
35
71
|
, new Object[]{id}
|
36
72
|
, new BeanPropertyRowMapper<Account>(Account.class));
|
37
73
|
}
|
74
|
+
}
|
38
75
|
```
|