-
Notifications
You must be signed in to change notification settings - Fork 76
Add Hibernate example with H2 in-memory database to idea-examples #1367
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletions
100
...ta-sources/src/main/kotlin/org/jetbrains/kotlinx/dataframe/examples/hibernate/entities.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
package org.jetbrains.kotlinx.dataframe.examples.hibernate | ||
|
||
import jakarta.persistence.Column | ||
import jakarta.persistence.Entity | ||
import jakarta.persistence.GeneratedValue | ||
import jakarta.persistence.GenerationType | ||
import jakarta.persistence.Id | ||
import jakarta.persistence.Table | ||
import org.jetbrains.kotlinx.dataframe.annotations.ColumnName | ||
import org.jetbrains.kotlinx.dataframe.annotations.DataSchema | ||
|
||
@Entity | ||
@Table(name = "Albums") | ||
class AlbumsEntity( | ||
@Id | ||
@GeneratedValue(strategy = GenerationType.IDENTITY) | ||
@Column(name = "AlbumId") | ||
var albumId: Int? = null, | ||
|
||
@Column(name = "Title", length = 160, nullable = false) | ||
var title: String = "", | ||
|
||
@Column(name = "ArtistId", nullable = false) | ||
var artistId: Int = 0, | ||
) | ||
|
||
@Entity | ||
@Table(name = "Artists") | ||
class ArtistsEntity( | ||
@Id | ||
@GeneratedValue(strategy = GenerationType.IDENTITY) | ||
@Column(name = "ArtistId") | ||
var artistId: Int? = null, | ||
|
||
@Column(name = "Name", length = 120, nullable = false) | ||
var name: String = "", | ||
) | ||
|
||
@Entity | ||
@Table(name = "Customers") | ||
class CustomersEntity( | ||
@Id | ||
@GeneratedValue(strategy = GenerationType.IDENTITY) | ||
@Column(name = "CustomerId") | ||
var customerId: Int? = null, | ||
|
||
@Column(name = "FirstName", length = 40, nullable = false) | ||
var firstName: String = "", | ||
|
||
@Column(name = "LastName", length = 20, nullable = false) | ||
var lastName: String = "", | ||
|
||
@Column(name = "Company", length = 80) | ||
var company: String? = null, | ||
|
||
@Column(name = "Address", length = 70) | ||
var address: String? = null, | ||
|
||
@Column(name = "City", length = 40) | ||
var city: String? = null, | ||
|
||
@Column(name = "State", length = 40) | ||
var state: String? = null, | ||
|
||
@Column(name = "Country", length = 40) | ||
var country: String? = null, | ||
|
||
@Column(name = "PostalCode", length = 10) | ||
var postalCode: String? = null, | ||
|
||
@Column(name = "Phone", length = 24) | ||
var phone: String? = null, | ||
|
||
@Column(name = "Fax", length = 24) | ||
var fax: String? = null, | ||
|
||
@Column(name = "Email", length = 60, nullable = false) | ||
var email: String = "", | ||
|
||
@Column(name = "SupportRepId") | ||
var supportRepId: Int? = null, | ||
) | ||
|
||
// DataFrame schema to get typed accessors similar to Exposed example | ||
@DataSchema | ||
data class DfCustomers( | ||
zaleslaw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@ColumnName("Address") val address: String?, | ||
@ColumnName("City") val city: String?, | ||
@ColumnName("Company") val company: String?, | ||
@ColumnName("Country") val country: String?, | ||
@ColumnName("CustomerId") val customerId: Int, | ||
@ColumnName("Email") val email: String, | ||
@ColumnName("Fax") val fax: String?, | ||
@ColumnName("FirstName") val firstName: String, | ||
@ColumnName("LastName") val lastName: String, | ||
@ColumnName("Phone") val phone: String?, | ||
@ColumnName("PostalCode") val postalCode: String?, | ||
@ColumnName("State") val state: String?, | ||
@ColumnName("SupportRepId") val supportRepId: Int?, | ||
) |
251 changes: 251 additions & 0 deletions
251
...d-data-sources/src/main/kotlin/org/jetbrains/kotlinx/dataframe/examples/hibernate/main.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,251 @@ | ||
package org.jetbrains.kotlinx.dataframe.examples.hibernate | ||
|
||
import jakarta.persistence.Tuple | ||
import jakarta.persistence.criteria.CriteriaBuilder | ||
import jakarta.persistence.criteria.CriteriaDelete | ||
import jakarta.persistence.criteria.CriteriaQuery | ||
import jakarta.persistence.criteria.Expression | ||
import jakarta.persistence.criteria.Root | ||
import org.hibernate.FlushMode | ||
import org.hibernate.SessionFactory | ||
import org.hibernate.cfg.Configuration | ||
import org.jetbrains.kotlinx.dataframe.DataFrame | ||
import org.jetbrains.kotlinx.dataframe.DataRow | ||
import org.jetbrains.kotlinx.dataframe.api.asSequence | ||
import org.jetbrains.kotlinx.dataframe.api.count | ||
import org.jetbrains.kotlinx.dataframe.api.describe | ||
import org.jetbrains.kotlinx.dataframe.api.groupBy | ||
import org.jetbrains.kotlinx.dataframe.api.print | ||
import org.jetbrains.kotlinx.dataframe.api.sortByDesc | ||
import org.jetbrains.kotlinx.dataframe.api.toDataFrame | ||
import org.jetbrains.kotlinx.dataframe.size | ||
|
||
/** | ||
* Example showing Kotlin DataFrame with Hibernate ORM + H2 in-memory DB. | ||
* Mirrors logic from the Exposed example: load data, convert to DataFrame, group/describe, write back. | ||
*/ | ||
fun main() { | ||
val sessionFactory: SessionFactory = buildSessionFactory() | ||
|
||
sessionFactory.insertSampleData() | ||
|
||
val df = sessionFactory.loadCustomersAsDataFrame() | ||
|
||
// Pure Hibernate + Criteria API approach for counting customers per country | ||
println("=== Hibernate + Criteria API Approach ===") | ||
sessionFactory.countCustomersPerCountryWithHibernate() | ||
|
||
println("\n=== DataFrame Approach ===") | ||
df.analyzeAndPrintResults() | ||
|
||
sessionFactory.replaceCustomersFromDataFrame(df) | ||
|
||
sessionFactory.close() | ||
} | ||
|
||
private fun SessionFactory.insertSampleData() { | ||
withTransaction { session -> | ||
// a few artists and albums (minimal, not used further; just demo schema) | ||
val artist1 = ArtistsEntity(name = "AC/DC") | ||
val artist2 = ArtistsEntity(name = "Queen") | ||
session.persist(artist1) | ||
session.persist(artist2) | ||
session.flush() | ||
|
||
session.persist(AlbumsEntity(title = "High Voltage", artistId = artist1.artistId!!)) | ||
session.persist(AlbumsEntity(title = "Back in Black", artistId = artist1.artistId!!)) | ||
session.persist(AlbumsEntity(title = "A Night at the Opera", artistId = artist2.artistId!!)) | ||
// customers we'll analyze using DataFrame | ||
session.persist( | ||
CustomersEntity( | ||
firstName = "John", | ||
lastName = "Doe", | ||
email = "[email protected]", | ||
country = "USA", | ||
), | ||
) | ||
session.persist( | ||
CustomersEntity( | ||
firstName = "Jane", | ||
lastName = "Smith", | ||
email = "[email protected]", | ||
country = "USA", | ||
), | ||
) | ||
session.persist( | ||
CustomersEntity( | ||
firstName = "Alice", | ||
lastName = "Wang", | ||
email = "[email protected]", | ||
country = "Canada", | ||
), | ||
) | ||
} | ||
} | ||
|
||
private fun SessionFactory.loadCustomersAsDataFrame(): DataFrame<DfCustomers> { | ||
return withReadOnlyTransaction { session -> | ||
val criteriaBuilder: CriteriaBuilder = session.criteriaBuilder | ||
val criteriaQuery: CriteriaQuery<CustomersEntity> = criteriaBuilder.createQuery(CustomersEntity::class.java) | ||
val root: Root<CustomersEntity> = criteriaQuery.from(CustomersEntity::class.java) | ||
criteriaQuery.select(root) | ||
|
||
session.createQuery(criteriaQuery) | ||
.resultList | ||
.map { c -> | ||
DfCustomers( | ||
address = c.address, | ||
city = c.city, | ||
company = c.company, | ||
country = c.country, | ||
customerId = c.customerId ?: -1, | ||
email = c.email, | ||
fax = c.fax, | ||
firstName = c.firstName, | ||
lastName = c.lastName, | ||
phone = c.phone, | ||
postalCode = c.postalCode, | ||
state = c.state, | ||
supportRepId = c.supportRepId, | ||
) | ||
} | ||
.toDataFrame() | ||
} | ||
} | ||
|
||
/** DTO used for aggregation projection. */ | ||
private data class CountryCountDto( | ||
val country: String, | ||
val customerCount: Long, | ||
) | ||
|
||
/** | ||
* **Hibernate + Criteria API:** | ||
* - ✅ Database-level aggregation (efficient) | ||
* - ✅ Type-safe queries | ||
* - ❌ Verbose syntax | ||
* - ❌ Limited to SQL-like operations | ||
*/ | ||
private fun SessionFactory.countCustomersPerCountryWithHibernate() { | ||
withReadOnlyTransaction { session -> | ||
val cb = session.criteriaBuilder | ||
val cq: CriteriaQuery<CountryCountDto> = cb.createQuery(CountryCountDto::class.java) | ||
val root: Root<CustomersEntity> = cq.from(CustomersEntity::class.java) | ||
|
||
val countryPath = root.get<String>("country") | ||
val idPath = root.get<Long>("customerId") | ||
|
||
val countExpr = cb.count(idPath) | ||
|
||
cq.select( | ||
cb.construct( | ||
CountryCountDto::class.java, | ||
countryPath, // country | ||
countExpr, // customerCount | ||
), | ||
) | ||
cq.groupBy(countryPath) | ||
cq.orderBy(cb.desc(countExpr)) | ||
|
||
val results = session.createQuery(cq).resultList | ||
results.forEach { dto -> | ||
println("${dto.country}: ${dto.customerCount} customers") | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* **DataFrame approach: ** | ||
* - ✅ Rich analytical operations | ||
* - ✅ Fluent, readable API | ||
* - ✅ Flexible data transformations | ||
* - ❌ In-memory processing (less efficient for large datasets) | ||
*/ | ||
private fun DataFrame<DfCustomers>.analyzeAndPrintResults() { | ||
println(size()) | ||
|
||
// same operation as Exposed example: customers per country | ||
groupBy { country }.count() | ||
zaleslaw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.sortByDesc { "count"<Int>() } | ||
.print(columnTypes = true, borders = true) | ||
|
||
// general statistics | ||
describe() | ||
.print(columnTypes = true, borders = true) | ||
} | ||
|
||
private fun SessionFactory.replaceCustomersFromDataFrame(df: DataFrame<DfCustomers>) { | ||
withTransaction { session -> | ||
val criteriaBuilder: CriteriaBuilder = session.criteriaBuilder | ||
val criteriaDelete: CriteriaDelete<CustomersEntity> = | ||
criteriaBuilder.createCriteriaDelete(CustomersEntity::class.java) | ||
criteriaDelete.from(CustomersEntity::class.java) | ||
|
||
session.createMutationQuery(criteriaDelete).executeUpdate() | ||
} | ||
|
||
withTransaction { session -> | ||
df.asSequence().forEach { row -> | ||
session.persist(row.toCustomersEntity()) | ||
} | ||
} | ||
} | ||
|
||
private fun DataRow<DfCustomers>.toCustomersEntity(): CustomersEntity { | ||
return CustomersEntity( | ||
customerId = null, // let DB generate | ||
firstName = this.firstName, | ||
lastName = this.lastName, | ||
company = this.company, | ||
address = this.address, | ||
city = this.city, | ||
state = this.state, | ||
country = this.country, | ||
postalCode = this.postalCode, | ||
phone = this.phone, | ||
fax = this.fax, | ||
email = this.email, | ||
supportRepId = this.supportRepId, | ||
) | ||
} | ||
|
||
private inline fun <T> SessionFactory.withSession(block: (session: org.hibernate.Session) -> T): T { | ||
return openSession().use(block) | ||
} | ||
|
||
private inline fun SessionFactory.withTransaction(block: (session: org.hibernate.Session) -> Unit) { | ||
withSession { session -> | ||
session.beginTransaction() | ||
try { | ||
block(session) | ||
session.transaction.commit() | ||
} catch (e: Exception) { | ||
session.transaction.rollback() | ||
throw e | ||
} | ||
} | ||
} | ||
|
||
/** Read-only transaction helper for SELECT queries to minimize overhead. */ | ||
private inline fun <T> SessionFactory.withReadOnlyTransaction(block: (session: org.hibernate.Session) -> T): T { | ||
return withSession { session -> | ||
session.beginTransaction() | ||
// Minimize overhead for read operations | ||
session.isDefaultReadOnly = true | ||
session.hibernateFlushMode = FlushMode.MANUAL | ||
try { | ||
val result = block(session) | ||
session.transaction.commit() | ||
result | ||
} catch (e: Exception) { | ||
session.transaction.rollback() | ||
throw e | ||
} | ||
} | ||
} | ||
|
||
|
||
private fun buildSessionFactory(): SessionFactory { | ||
// Load configuration from resources/hibernate/hibernate.cfg.xml | ||
return Configuration().configure("hibernate/hibernate.cfg.xml").buildSessionFactory() | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.