cours-05.html 15.6 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
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Programmation Web Avancée   Spring MVC, Injection de Dépendances</title>
<meta name="cours-n" content="5">

<meta name="author" content="Rémi Emonet">
<meta name="venue" content="PWA M1 DSC">
<meta name="date" content="2017">
<meta name="affiliation" content="Université Jean Monnet − Laboratoire Hubert Curien">
<style type="text/css">
.slide.densish>ul {font-size: 70%;}
</style>

<!--
<script src="deck.js/extensions/includedeck/load.js"></script>
<script src="extensions/slides-dev.js"></script>
-->
<script src="extensions/deck-packed.js"></script>
<script src="extensions/slides.js"></script>
<script>go()</script>
</head>

<body>

<div class="deck-container">

<div class="deck-loading-splash" style="background: black; color: chartreuse;"><span class="vcenter" style="font-size: 30px; font-family: Arial; ">Please wait, while our marmots are preparing the hot chocolate…</span></div>

<section class="smart">

# @chunk: chunks/title.md

# Questions ? <br/> Commentaires ? {no-print}

# @chunk: chunks/objectives.md

## Programmation Web Avancée <span>{var-cours-n}</span> : Plan {#plan overview}
- MVC Web et Spring MVC {mvcweb}
- MVC Web en Pratique {mvcdemo}
- Injection de Dépendances {di}
- Introduction à la persistance en Java {persi}
- Java Persistence API (JPA) {jpa}
# @copy:#plan




<!-- MVC Web Spring (et un peu Java EE) -->
# @copy:#plan: %+class:inred: .mvcweb

## MVC avec Spring dans ce cours {libyli}
- Modèle
- JavaBeans (objets Java)
- persistance avec JPA et Repositories de Spring Data
- Contrôleur
- description de route : annotations Java
- méthodes Java, avec injection de paramètres
- classe `Model` pour le ViewModel
- Vue
- templates Thymeleaf
- accès automatique au ViewModel


## Interaction Client Serveur et MVC
<p> </p>

@svg: media/client-server-mvc/server-mvc.svg 700px 400px

- @anim: #user, #client |#server |#r0 |#a0 |#s0,#router |#s1,#controller |#s2,#service |#s3,#db |#s4 |#s5,#view |#s6 |#s7 |#legend


<!-- ################################### -->
# @copy:#plan: %+class:inred: .mvcdemo

## Quelques Éléments en Vrac (+ astuces) {libyli densish}
- Pour tester on peut faire un modèle en mémoire
- sous forme d'objets Java
- stockés dans une liste dans une variable « globale »
- Un/des contrôleur(s) {libyli}
- annotation de classe `@Controller`
- annotation de méthode `@RequestMapping(.....)`
- paramètre « magique » `Model m`, qui sera passé à la vue
- `m.addAttribute("letruc", valeur)` pour remplir le « modèle de vue »
- paramètre et annotation `@RequestParameter` pour les formulaires {unseen}
- capture de pattern dans l'url avec `@PathVariable` {unseen}
- Une/des vue(s) {libyli}
- fichiers Thymeleaf = XHTML + `th:....` (templates dite naturelles)
- remplacer le contenu d'une balise, attribut `... th:text="${letruc}"`
- ...
- accès à une propriété d'un objet `${letruc.machin}{}` équivalent à `letruc.getMachin()` en Java
- répéter la balise donnée, attribut `... th:each="e : ${letruc}"`
- mélanger texte et variables dans une balise
- la balise doit avoir `th:inline="text"` (ou il faut utiliser Thymeleaf 3)
- dans la balise, utiliser des doubles crochets, e.g., `Bonjour [[${nom}]] !` {unseen}
- gérer les formulaires (cf TP) avec `th:action`, `th:object`, `th:field` {unseen}
- Convention maven (système de build) + Spring
- fichiers Java dans `src/main/java/.....`
- fichiers templates dans `src/main/resources/templates/`
- fichiers statiques dans `src/main/resources/static/` (pour les .css, .js, images etc)

# Start Démo

# modèle simple et affichage de la liste

# ajout "id" aux classe du modèle (pour la suppresison)

# `th:inline="text"`, lien détails (`th:href="@{....}"`)

# suppression, `@RequestParam`, `return "redirect:/....";`

# page de détails `@PathVariable`

# formulaire d'ajout avec `th:action` (et `th:object`, `th:field`, et constructeur vide)

# End Démo

<!-- ################################### -->
# @copy:#plan: %+class:inred: .di

## Injection de dépendance (DI) {libyli}
- Cas sans injection de dépendance
- il nous faut une instance (par ex, une connection DB)
- on la crée (ou on utilise une « Factory »)
- Patron « injection de dépendance »
- Dependency Injection (DI) Inversion of Control (IoC)
- quelqu'un fourni l'instance (e.g. avec `@Component`), qui est injectée dans notre programme
- injection par constructeur ou par “setter”
```java
class UserObject {
@Inject Connection connection;
@Inject BlablaService blabla;
}
{slide denser}
```
- Ce que fait à peu près le framework d'injection : il cherche des implémentations de Connection et BlablaService, puis
```java
Connection cDB = new SQLDataConnection();
BlablaService s = new BlaBlaServiceImpl();
UserObject obj = new UserObject();
obj.setConnection(cDB);
obj.setService(s);
{slide denser}
```

# Injectons avec `@Inject` et `@Component` (+ ajout de dépendance maven à javax.inject)




<!-- ###################### -->
# @copy:#plan: %+class:inred: .persi

## Persistence: motivation {libyli}
- When we close/restart an application
- memory is freed
- all objects are lost
- Persistence
- saving objects state
- ... on a permanent storage (non-volatile), e.g., database, file, etc
- allows for reloading objects later

## Persistence Options in Java {libyli}
- Simple JDBC with or without DAOs (DataAccessObjects)
- direct access to the SQL database
- DAO: object that encapsulates/hides SQL requests
- ORM Concept: Object-Relational Mapping
- systematic mapping between Java objects and database relations/tables
- Persistence Frameworks with ORM
- JPA (Java Persistence API) // most recent
- JDO (Java Data Objects) // most complete (more than JPA)
- EJB 3 (Entreprise JavaBeans) // higher level
- Hibernate (Spring), via JPA // just a JPA backend now


## Simple JDBC Example
```
import java.sql.*;
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) throws ... {

Class.forName(JDBC_DRIVER);

Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT id, prenom, nom, age FROM Employes");

while(rs.next()){

int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("prenom");
String last = rs.getString("nom");

System.out.print(id + " : " + first + " " + last + " agé de " + age);
}

rs.close(); // hum....
stmt.close(); // hum....
conn.close(); // hum....
}
{denser}
```
<div class="slide anim-show" data-dur="400" data-what="code>span:nth-of-type(-n+10)"></div>
<div class="slide anim-show" data-dur="400" data-what="code>span:nth-of-type(n+10):nth-of-type(-n+18)"></div>
<div class="slide anim-show" data-dur="400" data-what="code>span:nth-of-type(n+18):nth-of-type(-n+28)"></div>
<div class="slide anim-show" data-dur="400" data-what="code>span:nth-of-type(n+28):nth-of-type(-n+34)"></div>

## Simple JDBC example, Java 7+
```java
import java.sql.*;
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
 
public static void main(String[] args) throws ... {
 
Class.forName(JDBC_DRIVER);
 
try (
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, prenom, nom, age FROM Employes");
) {
 
while(rs.next()){
 
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("prenom");
String last = rs.getString("nom");
 
System.out.print(id + " : " + first + " " + last + " agé de " + age);
}
}
}
{denser}
```

# JDBC simple : avantages/inconvénients ?


## Objet-Relational Mapping: concept

- @anim: #objs |#rel |#car |#table |#arr0 |#arr1 |#arr2 |#arr3 |#arr4
- @anim: #optionClass |#optionTable |#arr678 |#optColumn |#arr5

@SVG: media/orm.svg 800 420



## Object-Relational Mapping {libyli}
- Questions?
- what class corresponds to what table
- what attribute corresponds to what column
- what attribute corresponds to what foreign key
- what are the multiplicities
- In practice{libyli}
- using JDBC, manually… tedious
- source code very long (most of the app) // 30%
- very repetitive code
- dangerous code (error-prone)
- difficult to evolve
- using a persistence framework
- JPA, JDO, Hibernate
- writing metadata on Java classes and attributes


<!-- ###################### -->
# @copy:#plan: %+class:inred: .jpa

## JPA: Java Persistance API {libyli}
- Why the JPA standard? {libyli}
- Pure JDBC: tedious
- Data Access Objects: abstraction, but too much code
- need a Object/Relational Mapping (ORM) description
- XML description too verbose and not DRY (Don't Repeat Yourself)
- proliferation of frameworks (hibernate, toplink, ...)
- need a usable standard
- What is JPA?
- a set of annotations and conventions // default values etc
- description of object/relational mappings
- originally, a part EJB 3 (Entreprise Java Beans)
- an `EntityManager` to manage data (transparent in Spring)
- to save, `em.persist()`
- to delete, `em.remove()`
- to read, `em.find()`, …

## JPA Annotations: simple example
```java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;



@Entity
public class Car {


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String company;
private String model;
private long price;
...constr/get/set... Important!
}

...

EntityManager em;
...
em.persist(myCar);
{}
```

## JPA Annotations: simple example
```java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
@Entity
@Table(name = "Vehicle")
public class Car {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "company")
private String company;
@Column(name = "model")
private String model;
@Column(name = "price")
private long price;
...constr/get/set... Important!
}
...
EntityManager em;
...
em.persist(myCar);
{}
```


## JPA Annotations // make them write something
- Others {right autre}
- @PersistenceContext // expliquer qu'il faut sauver les EJB
- …
- Class-level
- @Entity
- @Table
- (EJB @Stateless)
- (EJB @Stateful)
- …
- Attribute-level, JavaBean relations {right relations}
- @OneToOne
- @ManyToOne
- @OneToMany
- @ManyToMany
- @MapKey
- @OrderBy
- …
- Attribute-level, JavaBean {attr}
- @Column
- @Id
- @GeneratedValue
- @Temporal, @Lob, @Basic
- @Version
- @Transient
- …
- @anim: .attr | .relations | .autre

## Manipulating JPA Entities {libyli}
- (Using an `EntityManager`)
- to read, `em.find()`, …
- to save, `em.persist()`
- to delete, `em.remove()`
- Using `Repositories`
- abstraction to list and filter objects
- need to define an interface
- implemented automatically, e.g., by Spring Data
- interfaces: Repository, CrudRepository, PagingAndSortingRepository
- implementation is obtained via dependency injection

# JPA (`@Entity`, `@Id`, `@OneToMany`, ...), Spring Data (`CrudRepository` x2 + `.save`), `/TEST`

## What Did We Just Do? {libyli}
- Update the model
- add an `@Entity` on the class
- add a `long id` field, <br/> with `@Id @GeneratedValue(strategy=GenerationType.AUTO) {dense}`
- Create a new repository
- an (empty) interface (not a class)
- extending *CrudRepository&lt;MyEntity, Long>{smartcode}*
- Used the new repository interface
- injected it
- used `findAll` and `save`
- the implementation being provided by spring data
- According to project configuration (and defaults)
- spring automatically uses an H2 database
- the database is in memory (by default)
- the database schema is automatically created
- the database is dropped at startup

# Keeping Our Data! <br/> Tuning `application.properties{dense}`

## What Did We Just Do? {libyli}
- Changing project configuration
- to override default configuration
- adding key=value properties in `application.properties`
- Using a file database (instead of solely in-memory)
- `spring.datasource.url=jdbc:h2:/tmp/mytestdb`
- Stopped dropping (and recreating) the database everytime
- `spring.jpa.hibernate.ddl-auto=none`
- NB about previous point
- in case one need to re-create the databse (schema update)
- the line can be remove
- or, use `spring.jpa.hibernate.ddl-auto=create-drop`
- Some properties
- `spring.datasource.password`, `spring.datasource.username`
- `server.port`
- and <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html" target="_blank">WAY more</a>


# ORM : avantages/inconvénients ?


</section>

<!-- deck.status snippet -->
<p class="deck-status deck-progress-10"> <span class="deck-status-current"></span> / <span class="deck-status-total"></span><span class="var-author">will be replaced by the author</span><span class="var-title">will be replaced by the title</span></p>

<a data-progress-size=": spe.top(15, 555); height: 45*designRatio; left: slide.right - 90*designRatio; width: 90*designRatio" class="ccby" href="http://en.wikipedia.org/wiki/Creative_Commons_license" title="This work is under CC-BY licence." target="_blank"></a>

<a class="ujm" data-progress-size=": spe.top(15, 525); height: 65*designRatio; left: slide.left; width: 130*designRatio" target="_blank"></a>

</div>
<!-- clicky Cla -->
<script type="text/javascript">
var clicky_site_ids = clicky_site_ids || [];
clicky_site_ids.push(100779706);
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//static.getclicky.com/js';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( s );
})();
</script>
<noscript><p><img alt="Clicky" width="1" height="1" src="//in.getclicky.com/100779706ns.gif" /></p></noscript>


<!-- Histats.com START (aync)-->
<script type="text/javascript">var _Hasync= _Hasync|| [];
_Hasync.push(['Histats.start', '1,2767123,4,0,0,0,00010000']);
_Hasync.push(['Histats.fasi', '1']);
_Hasync.push(['Histats.track_hits', '']);
(function() {
var hs = document.createElement('script'); hs.type = 'text/javascript'; hs.async = true;
hs.src = ('http://s10.histats.com/js15_as.js');
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(hs);
})();</script>
<noscript><a href="http://www.histats.com" target="_blank"><img src="http://sstatic1.histats.com/0.gif?2767123&101" alt="javascript hit counter" border="0"></a></noscript>
<!-- Histats.com END -->
</body>
</html>