1
1
package com.baeldung.kotlin.jpa
2
2
3
3
import org.hibernate.Hibernate
4
+ import org.hibernate.Session
5
+ import org.hibernate.Transaction
4
6
import org.hibernate.cfg.Configuration
5
7
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase
6
- import org.hibernate.testing.transaction.TransactionUtil.doInHibernate
7
8
import org.junit.Assert.assertTrue
8
9
import org.junit.Test
9
10
import org.slf4j.LoggerFactory
@@ -32,9 +33,26 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
32
33
configuration.properties = properties
33
34
}
34
35
36
+ fun doInHibernate (action : (Session ) -> Unit ) {
37
+ val sessionFactory = sessionFactory()
38
+ val session = sessionFactory.openSession()
39
+ val transaction: Transaction = session.beginTransaction()
40
+
41
+ try {
42
+ action(session)
43
+ transaction.commit()
44
+ } catch (e: Exception ) {
45
+ transaction.rollback()
46
+ throw e
47
+ } finally {
48
+ session.close()
49
+ }
50
+ }
51
+
52
+
35
53
@Test
36
54
fun givenPersonWithFullData_whenSaved_thenFound () {
37
- doInHibernate(({ this .sessionFactory() })) { session ->
55
+ doInHibernate { session ->
38
56
val personToSave = Person (
39
57
" John" ,
40
58
@@ -49,7 +67,7 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
49
67
50
68
@Test
51
69
fun givenPerson_whenSaved_thenFound () {
52
- doInHibernate(({ this .sessionFactory() })) { session ->
70
+ doInHibernate { session ->
53
71
val personToSave = Person ( " John" )
54
72
session.persist(personToSave)
55
73
val personFound = session.find(Person ::class .java, personToSave.id)
@@ -61,7 +79,7 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
61
79
62
80
@Test
63
81
fun givenPersonWithNullFields_whenSaved_thenFound () {
64
- doInHibernate(({ this .sessionFactory() })) { session ->
82
+ doInHibernate { session ->
65
83
val personToSave = Person (" John" , null , null )
66
84
session.persist(personToSave)
67
85
val personFound = session.find(Person ::class .java, personToSave.id)
@@ -73,7 +91,7 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
73
91
74
92
@Test
75
93
fun givenAddressWithDefaultEquals_whenAddedToSet_thenNotFound () {
76
- doInHibernate({ sessionFactory() }) { session ->
94
+ doInHibernate{ session ->
77
95
val addresses = mutableSetOf<Address >()
78
96
val address = Address (name = " Berlin" , phoneNumbers = listOf (PhoneNumber ( " 42" )))
79
97
addresses.add(address)
@@ -86,7 +104,7 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
86
104
87
105
@Test
88
106
fun givenAddress_whenLogging_thenFetchesLazyAssociations () {
89
- doInHibernate({ this .sessionFactory() }) { session ->
107
+ doInHibernate{ session ->
90
108
val addressToSave = Address (name = " Berlin" , phoneNumbers = listOf (PhoneNumber (" 42" )))
91
109
session.persist(addressToSave)
92
110
session.clear()
0 commit comments