Skip to content

Commit 6da20ff

Browse files
author
eugenp
committed
spring data jpa work
1 parent 43cc23d commit 6da20ff

5 files changed

Lines changed: 316 additions & 7 deletions

File tree

‎spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
import org.baeldung.persistence.model.Foo;
44
import org.springframework.data.jpa.repository.JpaRepository;
55
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
6+
import org.springframework.data.jpa.repository.Query;
67

78
public interface IFooDao extends JpaRepository<Foo, Long>, JpaSpecificationExecutor<Foo> {
8-
//
9+
10+
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
11+
Foo retrieveByName(String name);
12+
913
}

‎spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public PersistenceConfig() {
3636
}
3737

3838
@Bean
39-
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
39+
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
4040
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
4141
em.setDataSource(dataSource());
4242
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
@@ -63,7 +63,7 @@ public DataSource dataSource() {
6363
@Bean
6464
public PlatformTransactionManager transactionManager() {
6565
final JpaTransactionManager transactionManager = new JpaTransactionManager();
66-
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
66+
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
6767

6868
return transactionManager;
6969
}
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
package org.baeldung.persistence.service;
2+
3+
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
4+
import static org.hamcrest.Matchers.hasItem;
5+
import static org.hamcrest.Matchers.not;
6+
import static org.junit.Assert.assertEquals;
7+
import static org.junit.Assert.assertNotNull;
8+
import static org.junit.Assert.assertNull;
9+
import static org.junit.Assert.assertThat;
10+
11+
import java.io.Serializable;
12+
import java.util.List;
13+
14+
import org.baeldung.persistence.IOperations;
15+
import org.baeldung.persistence.model.Foo;
16+
import org.baeldung.util.IDUtil;
17+
import org.hamcrest.Matchers;
18+
import org.junit.Ignore;
19+
import org.junit.Test;
20+
import org.springframework.dao.DataAccessException;
21+
22+
public abstract class AbstractServicePersistenceIntegrationTest<T extends Serializable> {
23+
24+
// tests
25+
26+
// find - one
27+
28+
@Test
29+
/**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() {
30+
// When
31+
final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong());
32+
33+
// Then
34+
assertNull(createdResource);
35+
}
36+
37+
@Test
38+
public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() {
39+
final Foo existingResource = persistNewEntity();
40+
getApi().findOne(existingResource.getId());
41+
}
42+
43+
@Test
44+
public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() {
45+
getApi().findOne(IDUtil.randomPositiveLong());
46+
}
47+
48+
@Test
49+
public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() {
50+
final Foo existingResource = persistNewEntity();
51+
final Foo retrievedResource = getApi().findOne(existingResource.getId());
52+
assertNotNull(retrievedResource);
53+
}
54+
55+
@Test
56+
public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() {
57+
final Foo existingResource = persistNewEntity();
58+
final Foo retrievedResource = getApi().findOne(existingResource.getId());
59+
assertEquals(existingResource, retrievedResource);
60+
}
61+
62+
// find - one - by name
63+
64+
// find - all
65+
66+
@Test
67+
/**/public void whenAllResourcesAreRetrieved_thenNoExceptions() {
68+
getApi().findAll();
69+
}
70+
71+
@Test
72+
/**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() {
73+
final List<Foo> resources = getApi().findAll();
74+
75+
assertNotNull(resources);
76+
}
77+
78+
@Test
79+
/**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() {
80+
persistNewEntity();
81+
82+
// When
83+
final List<Foo> allResources = getApi().findAll();
84+
85+
// Then
86+
assertThat(allResources, not(Matchers.<Foo> empty()));
87+
}
88+
89+
@Test
90+
/**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() {
91+
final Foo existingResource = persistNewEntity();
92+
93+
final List<Foo> resources = getApi().findAll();
94+
95+
assertThat(resources, hasItem(existingResource));
96+
}
97+
98+
@Test
99+
/**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() {
100+
persistNewEntity();
101+
102+
// When
103+
final List<Foo> allResources = getApi().findAll();
104+
105+
// Then
106+
for (final Foo resource : allResources) {
107+
assertNotNull(resource.getId());
108+
}
109+
}
110+
111+
// create
112+
113+
@Test(expected = RuntimeException.class)
114+
/**/public void whenNullResourceIsCreated_thenException() {
115+
getApi().create(null);
116+
}
117+
118+
@Test
119+
/**/public void whenResourceIsCreated_thenNoExceptions() {
120+
persistNewEntity();
121+
}
122+
123+
@Test
124+
/**/public void whenResourceIsCreated_thenResourceIsRetrievable() {
125+
final Foo existingResource = persistNewEntity();
126+
127+
assertNotNull(getApi().findOne(existingResource.getId()));
128+
}
129+
130+
@Test
131+
/**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() {
132+
final Foo originalResource = createNewEntity();
133+
final Foo savedResource = getApi().create(originalResource);
134+
135+
assertEquals(originalResource, savedResource);
136+
}
137+
138+
@Test(expected = RuntimeException.class)
139+
public void whenResourceWithFailedConstraintsIsCreated_thenException() {
140+
final Foo invalidResource = createNewEntity();
141+
invalidate(invalidResource);
142+
143+
getApi().create(invalidResource);
144+
}
145+
146+
/**
147+
* -- specific to the persistence engine
148+
*/
149+
@Test(expected = DataAccessException.class)
150+
@Ignore("Hibernate simply ignores the id silently and still saved (tracking this)")
151+
public void whenResourceWithIdIsCreated_thenDataAccessException() {
152+
final Foo resourceWithId = createNewEntity();
153+
resourceWithId.setId(IDUtil.randomPositiveLong());
154+
155+
getApi().create(resourceWithId);
156+
}
157+
158+
// update
159+
160+
@Test(expected = RuntimeException.class)
161+
/**/public void whenNullResourceIsUpdated_thenException() {
162+
getApi().update(null);
163+
}
164+
165+
@Test
166+
/**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() {
167+
// Given
168+
final Foo existingResource = persistNewEntity();
169+
170+
// When
171+
getApi().update(existingResource);
172+
}
173+
174+
/**
175+
* - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException
176+
*/
177+
@Test(expected = RuntimeException.class)
178+
public void whenResourceIsUpdatedWithFailedConstraints_thenException() {
179+
final Foo existingResource = persistNewEntity();
180+
invalidate(existingResource);
181+
182+
getApi().update(existingResource);
183+
}
184+
185+
@Test
186+
/**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() {
187+
// Given
188+
final Foo existingResource = persistNewEntity();
189+
190+
// When
191+
change(existingResource);
192+
getApi().update(existingResource);
193+
194+
final Foo updatedResource = getApi().findOne(existingResource.getId());
195+
196+
// Then
197+
assertEquals(existingResource, updatedResource);
198+
}
199+
200+
// delete
201+
202+
// @Test(expected = RuntimeException.class)
203+
// public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() {
204+
// // When
205+
// getApi().delete(IDUtil.randomPositiveLong());
206+
// }
207+
//
208+
// @Test(expected = RuntimeException.class)
209+
// public void whenResourceIsDeletedByNegativeId_thenException() {
210+
// // When
211+
// getApi().delete(IDUtil.randomNegativeLong());
212+
// }
213+
//
214+
// @Test
215+
// public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() {
216+
// // Given
217+
// final Foo existingResource = persistNewEntity();
218+
//
219+
// // When
220+
// getApi().delete(existingResource.getId());
221+
// }
222+
//
223+
// @Test
224+
// /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() {
225+
// // Given
226+
// final Foo existingResource = persistNewEntity();
227+
//
228+
// // When
229+
// getApi().delete(existingResource.getId());
230+
//
231+
// // Then
232+
// assertNull(getApi().findOne(existingResource.getId()));
233+
// }
234+
235+
// template method
236+
237+
protected Foo createNewEntity() {
238+
return new Foo(randomAlphabetic(6));
239+
}
240+
241+
protected abstract IOperations<Foo> getApi();
242+
243+
private final void invalidate(final Foo entity) {
244+
entity.setName(null);
245+
}
246+
247+
private final void change(final Foo entity) {
248+
entity.setName(randomAlphabetic(6));
249+
}
250+
251+
protected Foo persistNewEntity() {
252+
return getApi().create(createNewEntity());
253+
}
254+
255+
}

‎spring-security-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
44

5+
import org.baeldung.persistence.IOperations;
56
import org.baeldung.persistence.model.Foo;
67
import org.baeldung.spring.PersistenceConfig;
78
import org.junit.Ignore;
@@ -16,7 +17,7 @@
1617

1718
@RunWith(SpringJUnit4ClassRunner.class)
1819
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
19-
public class FooServicePersistenceIntegrationTest {
20+
public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest<Foo> {
2021

2122
@Autowired
2223
private IFooService service;
@@ -38,11 +39,20 @@ public final void whenInvalidEntityIsCreated_thenDataException() {
3839
service.create(new Foo());
3940
}
4041

41-
@Test(expected = DataIntegrityViolationException.class)
42-
public final void whenEntityWithLongNameIsCreated_thenDataException() {
43-
service.create(new Foo(randomAlphabetic(2048)));
42+
// @Test(expected = DataIntegrityViolationException.class)
43+
// public final void whenEntityWithLongNameIsCreated_thenDataException() {
44+
// service.create(new Foo(randomAlphabetic(2048)));
45+
// }
46+
47+
// custom Query method
48+
49+
@Test
50+
public final void givenUsingCustomQuery_whenExecuting_thenNoExceptions() {
51+
// service.create(new Foo(randomAlphabetic(2048)));
4452
}
4553

54+
// work in progress
55+
4656
@Test(expected = InvalidDataAccessApiUsageException.class)
4757
@Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail")
4858
public final void whenSameEntityIsCreatedTwice_thenDataException() {
@@ -51,4 +61,11 @@ public final void whenSameEntityIsCreatedTwice_thenDataException() {
5161
service.create(entity);
5262
}
5363

64+
// API
65+
66+
@Override
67+
protected final IOperations<Foo> getApi() {
68+
return service;
69+
}
70+
5471
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package org.baeldung.util;
2+
3+
import java.util.Random;
4+
5+
public final class IDUtil {
6+
7+
private IDUtil() {
8+
throw new AssertionError();
9+
}
10+
11+
// API
12+
13+
public final static String randomPositiveLongAsString() {
14+
return Long.toString(randomPositiveLong());
15+
}
16+
17+
public final static String randomNegativeLongAsString() {
18+
return Long.toString(randomNegativeLong());
19+
}
20+
21+
public final static long randomPositiveLong() {
22+
long id = new Random().nextLong() * 10000;
23+
id = (id < 0) ? (-1 * id) : id;
24+
return id;
25+
}
26+
27+
public final static long randomNegativeLong() {
28+
long id = new Random().nextLong() * 10000;
29+
id = (id > 0) ? (-1 * id) : id;
30+
return id;
31+
}
32+
33+
}

0 commit comments

Comments
 (0)