-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_java_jdbc_P_IntroductionJDBC.qmd.backup
More file actions
211 lines (171 loc) · 5.72 KB
/
Copy path03_java_jdbc_P_IntroductionJDBC.qmd.backup
File metadata and controls
211 lines (171 loc) · 5.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
---
title: TP JDBC
provide_notes: true
provide_slides: false
jupyter:
kernelspec:
display_name: 'Java [conda env:root] *'
language: java
name: conda-root-java
echo: true
output: true
categories:
- Java
- I111
- Exercices
- JDBC
---
## Schema and Basic Query
Dans la base de données relationnelles de votre choix créer une table `products` avec les colonnes suivantes (adapter si besoin):
```sql
CREATE TABLE IF NOT EXISTS products (
id IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO products (name, price) VALUES
('Laptop', 999.99),
('Mouse', 29.99),
('Keyboard', 59.99);
```
## Project Setp Up
### Maven Configuration
Create a new Maven project, adapt the `pom.xml` file:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>fr.iut</groupId>
<artifactId>jdbc-workshop</artifactId>
<version>0.1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
<scope>test</scope>
</dependency>
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.1</version>
</dependency>
<!-- Connection Pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.11.0</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
```
### Database Schema
Create schema files for both H2 and PostgreSQL:
```sql
// filepath: src/main/resources/schema-pg.sql
CREATE TABLE IF NOT EXISTS products (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
```sql
// filepath: src/main/resources/schema-h2.sql
CREATE TABLE IF NOT EXISTS products (
id IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
### Database Properties
```properties
// filepath: src/main/resources/database-pg.properties
db.url=jdbc:postgresql://localhost:5432/shop
db.username=postgres
db.password=postgres
db.pool.initialSize=5
db.pool.maxTotal=10
```
```properties
// filepath: src/test/resources/database-h2.properties
db.url=jdbc:h2:mem:shop;INIT=RUNSCRIPT FROM 'classpath:schema-h2.sql'
db.username=sa
db.password=
db.pool.initialSize=5
db.pool.maxTotal=10
```
## Simple Query Example
A partir de l'exemple suivant, écrire un programme Java qui se connecte à la base de données et affiche les produits enregistrés dans la table `products`:
```java
public class SimpleQueryExample {
private static Properties loadProperties() throws IOException {
Properties props = new Properties();
try (var input = SimpleQueryExample.class.getClassLoader()
.getResourceAsStream("database.properties")) {
props.load(input);
}
return props;
}
public static void main(String[] args) {
try {
Properties props = loadProperties();
Class.forName(props.getProperty("db.driver"));
try (Connection conn = DriverManager.getConnection(
props.getProperty("db.url"),
props.getProperty("db.user"),
props.getProperty("db.password"))) {
initSchema(conn);
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products")) {
System.out.println("Products in database:");
while (rs.next()) {
System.out.printf("ID: %d, Name: %s, Price: %.2f%n",
rs.getLong("id"),
rs.getString("name"),
rs.getDouble("price")
);
}
}
}
} catch (Exception e) {
System.err.println("Database error: " + e.getMessage());
e.printStackTrace();
}
}
}
```
## Une interface générique pour les opérations CRUD (DAO ou Repository)
En vous appuyant sur l'interface `CrudRepository` suivante, implémenter une classe `ProductRepository` qui permet de manipuler les produits en base de données:
```java
package com.example.dao;
import java.util.List;
import java.util.Optional;
public interface CrudRepository<T, ID> {
T save(T entity);
Optional<T> findById(ID id);
List<T> findAll();
void deleteById(ID id);
boolean existsById(ID id);
long count();
}
```
Utiliser la classe `ProductRepository` dans le programme principal pour créer, lire, mettre à jour et supprimer des produits.
## Exercice
Par équipe de 3 en utilisant le lien GitHub fournit adapter l'application de gestion des capteurs et mesures pour qu'elle utilise une base de données relationnelle pour stocker les données.