ソースを参照

jdbctemplate data source not find correct DB

Jonathan Hinds 7 年 前
コミット
da23b9d6fe

+ 9
- 0
data-h2.sql ファイルの表示

@@ -13,3 +13,12 @@ INSERT INTO PERSON ( LAST_NAME, FIRST_NAME, MOBILE, BIRTHDAY, HOME_ID)VALUES ('S
13 13
 INSERT INTO PERSON ( LAST_NAME, FIRST_NAME, MOBILE, BIRTHDAY, HOME_ID)VALUES ('Brown', 'Doug', '466-6241', '1954-12-07', 3);
14 14
 
15 15
 
16
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Howard the Duck',	110,	'Sci-Fi',	4.6,	'PG');
17
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Lavalantula',	83,	'Horror',	4.7,	'TV-14');
18
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Starship Troopers',	129,	'Sci-Fi',	7.2,	'PG-13');
19
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Waltz With Bashir',	90,	'Documentary',	8.0,	'R');
20
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Spaceballs',	96,	'Comedy',	7.1,	'PG');
21
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Monsters Inc.',	92,	'Animation',	8.1,	'G');
22
+
23
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Lords of Dogtown',	107,	'Sport',	7.1,	'PG-13');
24
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('A Beautiful Mind',	135,	'Drama',	8.2,	'PG-13');

+ 92
- 0
src/main/java/io/zipcoder/persistenceapp/Person.java ファイルの表示

@@ -0,0 +1,92 @@
1
+package io.zipcoder.persistenceapp;
2
+
3
+import javax.persistence.*;
4
+
5
+@Entity
6
+public class Person {
7
+
8
+    @Id
9
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
10
+    private Integer id;
11
+    private String firstName;
12
+    private String lastName;
13
+    private String mobile;
14
+    private String birthday;
15
+    private Integer homeId;
16
+
17
+    public Person() {
18
+        this.firstName = "firstName";
19
+        this.lastName = "lastName";
20
+        this.mobile = "mobile";
21
+        this.birthday = "2000-01-01";
22
+        this.homeId = 0;
23
+    }
24
+
25
+    public Person(String firstName, String lastName, String mobile, String birthday, int homeId) {
26
+        this.firstName = firstName;
27
+        this.lastName = lastName;
28
+        this.mobile = mobile;
29
+        this.birthday = birthday;
30
+        this.homeId = homeId;
31
+    }
32
+
33
+    public int getId() {
34
+        return id;
35
+    }
36
+
37
+    public void setId(int id) {
38
+        this.id = id;
39
+    }
40
+
41
+    public String getFirstName() {
42
+        return firstName;
43
+    }
44
+
45
+    public void setFirstName(String firstName) {
46
+        this.firstName = firstName;
47
+    }
48
+
49
+    public String getLastName() {
50
+        return lastName;
51
+    }
52
+
53
+    public void setLastName(String lastName) {
54
+        this.lastName = lastName;
55
+    }
56
+
57
+    public String getMobile() {
58
+        return mobile;
59
+    }
60
+
61
+    public void setMobile(String mobile) {
62
+        this.mobile = mobile;
63
+    }
64
+
65
+    public String getBirthday() {
66
+        return birthday;
67
+    }
68
+
69
+    public void setBirthday(String birthday) {
70
+        this.birthday = birthday;
71
+    }
72
+
73
+    public int getHomeId() {
74
+        return homeId;
75
+    }
76
+
77
+    public void setHomeId(int homeId) {
78
+        this.homeId = homeId;
79
+    }
80
+
81
+    @Override
82
+    public String toString() {
83
+        return "Person{" +
84
+                "id=" + id +
85
+                ", firstName='" + firstName + '\'' +
86
+                ", lastName='" + lastName + '\'' +
87
+                ", mobile='" + mobile + '\'' +
88
+                ", birthday='" + birthday + '\'' +
89
+                ", homeId=" + homeId +
90
+                '}';
91
+    }
92
+}

+ 105
- 0
src/main/java/io/zipcoder/persistenceapp/PersonController.java ファイルの表示

@@ -0,0 +1,105 @@
1
+package io.zipcoder.persistenceapp;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.http.HttpStatus;
5
+import org.springframework.http.ResponseEntity;
6
+import org.springframework.web.bind.annotation.*;
7
+
8
+import java.util.ArrayList;
9
+import java.util.List;
10
+import java.util.Map;
11
+
12
+@RestController
13
+public class PersonController {
14
+
15
+    @Autowired
16
+    PersonService serv;
17
+
18
+    @PostMapping("/people")
19
+    public Person createPerson(@RequestBody Person person){
20
+        int id = serv.savePerson(person);
21
+        person.setId(id);
22
+        return person;
23
+    }
24
+
25
+    @PutMapping("/people/{id}")
26
+    @ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Person not found.")
27
+    public Person updatePerson(@PathVariable int id, @RequestBody Person updatedPerson){
28
+        Person p = serv.findById(id);
29
+        updatedPerson.setId(p.getId());
30
+        if( p != null ) {
31
+            serv.updatePerson(updatedPerson);
32
+        } else {
33
+            new ResponseEntity(HttpStatus.NOT_FOUND);
34
+        }
35
+        return null;
36
+    }
37
+
38
+    @GetMapping("/people")
39
+    public List<Person> getAllPeople(){
40
+        return serv.getAllPeople();
41
+    }
42
+
43
+    @GetMapping("/people/{id}")
44
+    public Person getPersonById(@PathVariable int id){
45
+        return serv.findById(id);
46
+    }
47
+
48
+    @DeleteMapping("/people/{id}")
49
+    public Person deletePersonById(@PathVariable int id){
50
+        Person person = serv.findById(id);
51
+        serv.deletePerson(person);
52
+        return null;
53
+    }
54
+
55
+
56
+    @GetMapping("/people/reverselookup/{mobileNumber}")
57
+    public List<Person> getPeopleByNumber(@PathVariable String mobileNumber){
58
+        List<Person> people = serv.getAllPeople();
59
+        List<Person> peopleWithNumber = new ArrayList<>();
60
+        for(Person person : people){
61
+            if(person.getMobile().equals(mobileNumber)){
62
+                peopleWithNumber.add(person);
63
+            }
64
+        }
65
+       return peopleWithNumber;
66
+    }
67
+
68
+    @GetMapping("/people/surname/{lastName}")
69
+    public List<Person> getAllByLastName(@PathVariable String lastName){
70
+        Map<String, List<Person>> map = serv.surnameQuery();
71
+        for(String key : map.keySet()){
72
+            if(key.equals(lastName)){
73
+                return map.get(key);
74
+            }
75
+        }
76
+        return null;
77
+    }
78
+
79
+    @GetMapping("/people/surname")
80
+    public String getSurnameReport(){
81
+        String report = "";
82
+        Map<String, List<Person>> map = serv.surnameQuery();
83
+        for(String key : map.keySet()){
84
+            report += key + ": \n";
85
+            for(Person person : map.get(key)){
86
+                report += person.toString() + "\n";
87
+            }
88
+        }
89
+        return report;
90
+    }
91
+
92
+    @GetMapping("/people/firstname/stats")
93
+    public String getFirstNameCount(){
94
+        //Get the report of first name frequencies
95
+        String report = "";
96
+        Map<String, Integer> map = serv.firstNameCount();
97
+        for(String name : map.keySet()){
98
+            report += name + ", amount: " + map.get(name);
99
+        }
100
+        return report;
101
+    }
102
+
103
+
104
+
105
+}

+ 107
- 0
src/main/java/io/zipcoder/persistenceapp/PersonService.java ファイルの表示

@@ -0,0 +1,107 @@
1
+package io.zipcoder.persistenceapp;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.jdbc.core.JdbcTemplate;
5
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
6
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
7
+import org.springframework.jdbc.core.namedparam.SqlParameterSource;
8
+import org.springframework.jdbc.support.GeneratedKeyHolder;
9
+import org.springframework.jdbc.support.KeyHolder;
10
+import org.springframework.stereotype.Service;
11
+
12
+import java.util.ArrayList;
13
+import java.util.HashMap;
14
+import java.util.List;
15
+import java.util.Map;
16
+
17
+@Service
18
+public class PersonService {
19
+
20
+    @Autowired
21
+    private JdbcTemplate jdbcTemplate;
22
+
23
+    @Autowired
24
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
25
+
26
+
27
+    public List<Person> getAllPeople(){
28
+        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM PERSON");
29
+        List<Person> people = new ArrayList<>();
30
+        for (Map<String, Object> row : list) {
31
+            Person person = new Person(String.valueOf(row.get("FIRST_NAME")), String.valueOf(row.get("LAST_NAME")), String.valueOf(row.get("MOBILE")), row.get("BIRTHDAY").toString(), (Short)row.get("HOME_ID"));
32
+            person.setId((Integer)row.get("ID"));
33
+            people.add(person);
34
+        }
35
+        return people;
36
+    }
37
+
38
+    public int savePerson(Person e){
39
+        System.out.println(e.toString());
40
+        KeyHolder holder = new GeneratedKeyHolder();
41
+        SqlParameterSource parameters = new MapSqlParameterSource()
42
+                .addValue("first_name", e.getFirstName())
43
+                .addValue("last_name", e.getLastName())
44
+                .addValue("mobile", e.getMobile())
45
+                .addValue("birthday", e.getBirthday())
46
+                .addValue("home_id", e.getHomeId());
47
+
48
+        namedParameterJdbcTemplate.update("INSERT INTO PERSON (FIRST_NAME, LAST_NAME, MOBILE, BIRTHDAY, HOME_ID) VALUES (:first_name, :last_name, :mobile, :birthday, :home_id);", parameters, holder);
49
+        return holder.getKey().intValue();
50
+    }
51
+
52
+    public int updatePerson(Person e){
53
+        return jdbcTemplate.update("UPDATE PERSON SET FIRST_NAME = '" +
54
+                e.getFirstName() + "', LAST_NAME = '" +
55
+                e.getLastName() + "', MOBILE = '" +
56
+                e.getMobile() + "', BIRTHDAY = '" +
57
+                e.getBirthday() + "', HOME_ID = '" +
58
+                e.getHomeId() + "' where id = '" + e.getId() + "');");
59
+    }
60
+
61
+    public int deletePerson(Person e){
62
+        return jdbcTemplate.update("DELETE FROM PERSON where ID = " + e.getId() + ";");
63
+    }
64
+
65
+    public void removeList(Person... e){
66
+        for(Person person : e){
67
+            deletePerson(person);
68
+        }
69
+    }
70
+
71
+    public List<Person> findAllByFirstName(String firstName, Class objectType){
72
+        return jdbcTemplate.queryForList("SELECT * FROM PERSON WHERE FIRST_NAME = '" + firstName + "';", Person.class);
73
+    }
74
+
75
+    public Person findById(int ID){
76
+        return jdbcTemplate.queryForObject("SELECT * FROM PERSON WHERE ID = " + ID + ";", Person.class);
77
+    }
78
+
79
+    public Map<String, List<Person>> surnameQuery(){
80
+        List<Person> people = getAllPeople();
81
+        Map<String, List<Person>> map = new HashMap<>();
82
+        for(Person person : people){
83
+            if(map.containsKey(person.getLastName())){
84
+                map.get(person.getLastName()).add(person);
85
+            } else {
86
+                map.put(person.getLastName(), new ArrayList<Person>());
87
+                map.get(person.getLastName()).add(person);
88
+            }
89
+        }
90
+        return map;
91
+    }
92
+
93
+    public Map<String, Integer> firstNameCount(){
94
+        List<Person> people = getAllPeople();
95
+        Map<String, Integer> map = new HashMap<>();
96
+        for(Person person : people){
97
+            if(map.containsKey(person.getFirstName())){
98
+                int amount = map.get(person.getFirstName());
99
+                amount = amount + 1;
100
+                map.put(person.getFirstName(), amount);
101
+            } else {
102
+                map.put(person.getFirstName(), 1);
103
+            }
104
+        }
105
+        return map;
106
+    }
107
+}

+ 26
- 0
src/main/resources/Qs ファイルの表示

@@ -0,0 +1,26 @@
1
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Howard the Duck',	110,	'Sci-Fi',	4.6,	'PG');
2
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Lavalantula',	83,	'Horror',	4.7,	'TV-14');
3
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Starship Troopers',	129,	'Sci-Fi',	7.2,	'PG-13');
4
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Waltz With Bashir',	90,	'Documentary',	8.0,	'R');
5
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Spaceballs',	96,	'Comedy',	7.1,	'PG');
6
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Monsters Inc.',	92,	'Animation',	8.1,	'G');
7
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('Lords of Dogtown',	107,	'Sport',	7.1,	'PG-13');
8
+INSERT INTO MOVIES (Title, Runtime, Genre, IMDB_Score, Rating) VALUES ('A Beautiful Mind',	135,	'Drama',	8.2,	'PG-13');
9
+
10
+select * from movies where genre = 'Sci-Fi'
11
+
12
+select * from movies where IMDB_SCORE > 6.5
13
+
14
+select * from movies where rating = 'G' or rating = 'PG' and RUNTIME < 100
15
+
16
+select AVG(RUNTIME) from movies where IMDB_SCORE < 7.5 group by genre
17
+
18
+update movies set rating = 'R' where title = 'Starship Troopers'
19
+
20
+select rating, id from movies where genre = 'Horror' or genre = 'Documentary' order by rating
21
+
22
+select avg(IMDB_SCORE), rating from movies group by rating
23
+
24
+select rating from movies group by rating HAVING COUNT(*) > 1
25
+
26
+delete from movies where rating = 'R'

+ 7
- 2
src/main/resources/application-h2.properties ファイルの表示

@@ -1,4 +1,9 @@
1
-spring.datasource.url=jdbc:h2:mem:testdb;Mode=Oracle
1
+spring.profiles.active=h2
2
+logging.level.org.springframework.boot.context.embedded=INFO
3
+spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
4
+
5
+spring.datasource.url=jdbc:h2:mem:test;Mode=Oracle
2 6
 spring.datasource.platform=h2
3 7
 spring.jpa.hibernate.ddl-auto=none
4
-spring.datasource.continue-on-error=true
8
+spring.datasource.continue-on-error=true
9
+spring.h2.console.enabled=true

+ 2
- 1
src/main/resources/application.properties ファイルの表示

@@ -1,3 +1,4 @@
1 1
 spring.profiles.active=h2
2 2
 logging.level.org.springframework.boot.context.embedded=INFO
3
-spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
3
+spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
4
+