1
1
package com .baeldung .hibernate ;
2
2
3
+ import static org .assertj .core .api .Assertions .assertThat ;
4
+ import static org .assertj .core .api .Assertions .assertThatThrownBy ;
5
+
6
+ import java .io .IOException ;
7
+
8
+ import org .hibernate .Session ;
9
+ import org .hibernate .Transaction ;
10
+ import org .hibernate .id .IdentifierGenerationException ;
3
11
import org .junit .After ;
4
12
import org .junit .Before ;
5
13
import org .junit .Test ;
6
- import org .hibernate .Transaction ;
7
- import java .io .IOException ;
8
- import org .hibernate .Session ;
9
14
10
- import static org .assertj .core .api .Assertions .assertThat ;
11
-
12
- import com .baeldung .hibernate .pojo .Product ;
15
+ import com .baeldung .hibernate .pojo .BaseballPlayer ;
13
16
import com .baeldung .hibernate .pojo .Course ;
14
17
import com .baeldung .hibernate .pojo .OrderEntry ;
15
18
import com .baeldung .hibernate .pojo .OrderEntryIdClass ;
16
19
import com .baeldung .hibernate .pojo .OrderEntryPK ;
20
+ import com .baeldung .hibernate .pojo .Product ;
17
21
import com .baeldung .hibernate .pojo .Student ;
22
+ import com .baeldung .hibernate .pojo .TennisPlayer ;
18
23
import com .baeldung .hibernate .pojo .User ;
19
24
import com .baeldung .hibernate .pojo .UserProfile ;
20
25
21
26
public class IdentifiersIntegrationTest {
27
+
22
28
private Session session ;
23
29
24
30
private Transaction transaction ;
@@ -37,12 +43,32 @@ public void tearDown() {
37
43
}
38
44
39
45
@ Test
40
- public void whenSaveSimpleIdEntities_thenOk () {
46
+ public void whenSavingTennisPlayerWithoutAnId_thenSavingEntityOk () {
47
+ TennisPlayer tennisPlayer = new TennisPlayer ("Tom" );
48
+ session .save (tennisPlayer );
49
+ assertThat (tennisPlayer .getPlayerId ()).isEqualTo (0L );
50
+ }
51
+
52
+ @ Test
53
+ public void whenSavingBaseballPlayerWithoutAnId_thenSavingEntityFails () {
54
+ BaseballPlayer baseballPlayer = new BaseballPlayer ("Jerry" );
55
+ assertThatThrownBy (() -> session .save (baseballPlayer )).isInstanceOf (IdentifierGenerationException .class )
56
+ .hasMessageContaining ("ids for this class must be manually assigned before calling save()" );
57
+ }
58
+ @ Test
59
+ public void whenSavingBaseballPlayerWithAManualId_thenSavingEntityOK () {
60
+ BaseballPlayer baseballPlayer = new BaseballPlayer ("Jerry" );
61
+ baseballPlayer .setPlayerId (42L );
62
+ session .save (baseballPlayer );
63
+ }
64
+
65
+ @ Test
66
+ public void whenSaveSequenceIdEntities_thenOk () {
41
67
Student student = new Student ();
42
68
session .save (student );
43
69
User user = new User ();
44
70
session .save (user );
45
-
71
+
46
72
assertThat (student .getStudentId ()).isEqualTo (1L );
47
73
assertThat (user .getUserId ()).isEqualTo (4L );
48
74
@@ -103,4 +129,4 @@ public void whenSaveDerivedIdEntity_thenOk() {
103
129
assertThat (profile .getProfileId ()).isEqualTo (user .getUserId ());
104
130
}
105
131
106
- }
132
+ }
0 commit comments