Skip to content

Commit 467f647

Browse files
committed
iluwatar#590 add explanation for Repository
1 parent a18c0f7 commit 467f647

1 file changed

Lines changed: 231 additions & 5 deletions

File tree

‎repository/README.md‎

Lines changed: 231 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,236 @@ tags:
99
---
1010

1111
## Intent
12-
Repository layer is added between the domain and data mapping
13-
layers to isolate domain objects from details of the database access code and
14-
to minimize scattering and duplication of query code. The Repository pattern is
15-
especially useful in systems where number of domain classes is large or heavy
16-
querying is utilized.
12+
Repository layer is added between the domain and data mapping layers to isolate domain objects from details of the
13+
database access code and to minimize scattering and duplication of query code. The Repository pattern is especially
14+
useful in systems where number of domain classes is large or heavy querying is utilized.
15+
16+
## Explanation
17+
Real world example
18+
19+
> Let's say we need a persistent data store for persons. Adding new persons and searching for them according to different criteria must be easy.
20+
21+
In plain words
22+
23+
> Repository architectural pattern creates a uniform layer of data repositories that can be used for CRUD operations.
24+
25+
[Microsoft documentation](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design) says
26+
27+
> Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.
28+
29+
**Programmatic Example**
30+
31+
Let's first look at the person class that we need to persist.
32+
33+
```java
34+
@Entity
35+
public class Person {
36+
37+
@Id
38+
@GeneratedValue
39+
private Long id;
40+
private String name;
41+
private String surname;
42+
43+
private int age;
44+
45+
public Person() {
46+
}
47+
48+
/**
49+
* Constructor.
50+
*/
51+
public Person(String name, String surname, int age) {
52+
this.name = name;
53+
this.surname = surname;
54+
this.age = age;
55+
}
56+
57+
public Long getId() {
58+
return id;
59+
}
60+
61+
public void setId(Long id) {
62+
this.id = id;
63+
}
64+
65+
public String getName() {
66+
return name;
67+
}
68+
69+
public void setName(String name) {
70+
this.name = name;
71+
}
72+
73+
public String getSurname() {
74+
return surname;
75+
}
76+
77+
public void setSurname(String surname) {
78+
this.surname = surname;
79+
}
80+
81+
public int getAge() {
82+
return age;
83+
}
84+
85+
public void setAge(int age) {
86+
this.age = age;
87+
}
88+
89+
@Override
90+
public String toString() {
91+
return "Person [id=" + id + ", name=" + name + ", surname=" + surname + ", age=" + age + "]";
92+
}
93+
94+
@Override
95+
public int hashCode() {
96+
final var prime = 31;
97+
var result = 1;
98+
result = prime * result + age;
99+
result = prime * result + (id == null ? 0 : id.hashCode());
100+
result = prime * result + (name == null ? 0 : name.hashCode());
101+
result = prime * result + (surname == null ? 0 : surname.hashCode());
102+
return result;
103+
}
104+
105+
@Override
106+
public boolean equals(Object obj) {
107+
if (this == obj) {
108+
return true;
109+
}
110+
if (obj == null) {
111+
return false;
112+
}
113+
if (getClass() != obj.getClass()) {
114+
return false;
115+
}
116+
var other = (Person) obj;
117+
if (age != other.age) {
118+
return false;
119+
}
120+
if (id == null) {
121+
if (other.id != null) {
122+
return false;
123+
}
124+
} else if (!id.equals(other.id)) {
125+
return false;
126+
}
127+
if (name == null) {
128+
if (other.name != null) {
129+
return false;
130+
}
131+
} else if (!name.equals(other.name)) {
132+
return false;
133+
}
134+
if (surname == null) {
135+
return other.surname == null;
136+
}
137+
return surname.equals(other.surname);
138+
}
139+
}
140+
```
141+
142+
We are using Spring Data to create the repository so it becomes really simple.
143+
144+
```java
145+
@Repository
146+
public interface PersonRepository
147+
extends CrudRepository<Person, Long>, JpaSpecificationExecutor<Person> {
148+
149+
Person findByName(String name);
150+
}
151+
```
152+
153+
Additionally we define a helper class for specification queries.
154+
155+
```java
156+
public class PersonSpecifications {
157+
158+
public static class AgeBetweenSpec implements Specification<Person> {
159+
160+
private int from;
161+
162+
private int to;
163+
164+
public AgeBetweenSpec(int from, int to) {
165+
this.from = from;
166+
this.to = to;
167+
}
168+
169+
@Override
170+
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
171+
return cb.between(root.get("age"), from, to);
172+
}
173+
174+
}
175+
176+
public static class NameEqualSpec implements Specification<Person> {
177+
178+
public String name;
179+
180+
public NameEqualSpec(String name) {
181+
this.name = name;
182+
}
183+
184+
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
185+
return cb.equal(root.get("name"), this.name);
186+
}
187+
}
188+
189+
}
190+
```
191+
192+
And here's the repository in action.
193+
194+
```java
195+
var peter = new Person("Peter", "Sagan", 17);
196+
var nasta = new Person("Nasta", "Kuzminova", 25);
197+
var john = new Person("John", "lawrence", 35);
198+
var terry = new Person("Terry", "Law", 36);
199+
200+
repository.save(peter);
201+
repository.save(nasta);
202+
repository.save(john);
203+
repository.save(terry);
204+
205+
LOGGER.info("Count Person records: {}", repository.count());
206+
207+
var persons = (List<Person>) repository.findAll();
208+
persons.stream().map(Person::toString).forEach(LOGGER::info);
209+
210+
nasta.setName("Barbora");
211+
nasta.setSurname("Spotakova");
212+
repository.save(nasta);
213+
214+
repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p));
215+
repository.deleteById(2L);
216+
217+
LOGGER.info("Count Person records: {}", repository.count());
218+
219+
repository
220+
.findOne(new PersonSpecifications.NameEqualSpec("John"))
221+
.ifPresent(p -> LOGGER.info("Find by John is {}", p));
222+
223+
persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
224+
225+
LOGGER.info("Find Person with age between 20,40: ");
226+
persons.stream().map(Person::toString).forEach(LOGGER::info);
227+
228+
repository.deleteAll();
229+
230+
// Count Person records: 4
231+
// Person [id=1, name=Peter, surname=Sagan, age=17]
232+
// Person [id=2, name=Nasta, surname=Kuzminova, age=25]
233+
// Person [id=3, name=John, surname=lawrence, age=35]
234+
// Person [id=4, name=Terry, surname=Law, age=36]
235+
// Find by id 2: Person [id=2, name=Barbora, surname=Spotakova, age=25]
236+
// Count Person records: 3
237+
// Find by John is Person [id=3, name=John, surname=lawrence, age=35]
238+
// Find Person with age between 20,40:
239+
// Person [id=3, name=John, surname=lawrence, age=35]
240+
// Person [id=4, name=Terry, surname=Law, age=36]
241+
```
17242

18243
## Class diagram
19244
![alt text](./etc/repository.png "Repository")
@@ -36,3 +261,4 @@ Use the Repository pattern when
36261
* [Advanced Spring Data JPA - Specifications and Querydsl](https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/)
37262
* [Repository Pattern Benefits and Spring Implementation](https://stackoverflow.com/questions/40068965/repository-pattern-benefits-and-spring-implementation)
38263
* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321127420&linkCode=as2&tag=javadesignpat-20&linkId=d9f7d37b032ca6e96253562d075fcc4a)
264+
* [Design patterns that I often avoid: Repository pattern](https://www.infoworld.com/article/3117713/design-patterns-that-i-often-avoid-repository-pattern.html)

0 commit comments

Comments
 (0)