Hibernate cascading with no cascade types set (hibernate+kotlin)

Hibernate cascading with no cascade types set (hibernate+kotlin)

Hey guys, I’m having an issue where hibernate is cascading the

merge

operation to child entities when I don’t want it to. I have my entities pasted at the bottom of this post.

I’m trying to merge the

Munch

entity without merging any

Swipes

since they’re handled in a different part of the application. My understanding is that hibernate by default should

cascade

none of the DB operations for a

@OneToMany

collection or a

@ManyToOne

object unless

CascadeTypes

are explicitly specified.

Given the entities at the bottom of the post, when I add a

Swipe

to

munch.swipes

and run the following code, the munch is updated if any of its fields have changed and the added swipe is merged into the db:

 fun mergeMunch( munch: Munch ) = databaseExecutor.executeAndRollbackOnFailure { entityManager -> entityManager.merge(munch) entityManager.transaction.commit() }

If anyone could shed some light on either what I’m misunderstanding or misconfiguring it would be much appreciated.

The

executeAndRollbackOnFailure()

function just in case its useful:

 fun <T> executeAndRollbackOnFailure( task: (EntityManager) -> T ): T { val em = emf.createEntityManager() return try { em.transaction.begin() task.invoke(em) } catch (e: Exception) { em.transaction.rollback() throw e } finally { em.close() } }

Here are my entities:

Munch

“`

@Entity @TypeDefs( TypeDef( name = “list-array”, typeClass = ListArrayType::class ) ) data class Munch( @Column val name: String, @OneToMany( fetch = FetchType.LAZY, mappedBy = “munch”, ) val swipes: MutableList<Swipe> = mutableListOf(), ) { @Id @GenericGenerator(name = “generator”, strategy = “uuid”) @GeneratedValue(generator = “generator”) lateinit var munchId: String


fun addSwipe(swipe: Swipe) { swipes.add(swipe) swipe.munch = this }

} “`

Swipe

“` @Entity data class Swipe( @EmbeddedId val swipeIdKey: SwipeIdKey, @Column(nullable = true) val liked: Boolean, ) : Serializable { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = “munchId”) @MapsId(“munchId”) lateinit var munch: Munch


@Transient var updated = false

“`

SwipeIdKey

“` @Embeddable class SwipeIdKey : Serializable {


@Column(nullable = false) lateinit var restaurantId: String @Column(nullable = true) lateinit var userId: String @Column(nullable = true) var munchId: String? = null

} “`

submitted by /u/Iarduino
[link] [comments]