-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathjdbc-vs-jpa.yaml
More file actions
73 lines (71 loc) · 2.32 KB
/
Copy pathjdbc-vs-jpa.yaml
File metadata and controls
73 lines (71 loc) · 2.32 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
---
id: 9a27cf95-647d-49fd-a523-80ef7fdc4215
slug: "jdbc-vs-jpa"
title: "JDBC versus JPA"
category: "enterprise"
navigationOrder: 121000
difficulty: "intermediate"
jdkVersion: "11"
oldLabel: "Java EE"
modernLabel: "Jakarta EE 8+"
oldApproach: "JDBC"
modernApproach: "JPA EntityManager"
oldCode: |-
String sql = "SELECT * FROM users WHERE id = ?";
try (Connection con = dataSource.getConnection();
PreparedStatement ps =
con.prepareStatement(sql)) {
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
User u = new User();
u.setId(rs.getLong("id"));
u.setName(rs.getString("name"));
}
}
modernCode: |-
@PersistenceContext
EntityManager em;
public User findUser(Long id) {
return em.find(User.class, id);
}
public List<User> findByName(String name) {
return em.createQuery(
"SELECT u FROM User u WHERE u.name = :name",
User.class)
.setParameter("name", name)
.getResultList();
}
summary: "Replace verbose JDBC boilerplate with JPA's object-relational mapping and\
\ EntityManager."
explanation: "JPA (Jakarta Persistence API) maps Java objects to database rows, eliminating\
\ manual ResultSet processing and SQL string concatenation. EntityManager provides\
\ find(), persist(), and JPQL queries so you work with domain objects instead of\
\ raw SQL, while the container manages connection pooling and transactions."
whyModernWins:
- icon: "🗺️"
title: "Object mapping"
desc: "Entities are plain annotated classes — no manual ResultSet-to-object translation."
- icon: "🔒"
title: "Type-safe queries"
desc: "JPQL operates on entity types and fields rather than raw table and column\
\ strings."
- icon: "⚡"
title: "Built-in caching"
desc: "First- and second-level caches reduce database round-trips automatically."
support:
state: "available"
description: "Widely available since Jakarta EE 8 / Java 11"
related:
- "enterprise/servlet-vs-jaxrs"
- "enterprise/ejb-vs-cdi"
- "io/try-with-resources-effectively-final"
tags:
- enterprise
- persistence
- jpa
docs:
- title: "Jakarta Persistence Specification"
href: "https://jakarta.ee/specifications/persistence/"
- title: "Jakarta Persistence 3.1 API"
href: "https://jakarta.ee/specifications/persistence/3.1/apidocs/"