Skip to content

Conversation

@tristanlins
Copy link

The current implementation only generates IDs for NULL values.
But in JPA or in particular Hibernate generates a new ID for all unmanaged entities (If an ID generator is used).

In Kotlin in particular, this can be exploited as follows:

@Entity
data class Media(
  @Id
  @Column(nullable = false)
  @GeneratedValue
  var id: UUID = UUID(0, 0)
)

The "id" field is initialized with a 0-UUID and is never NULL.
This is a popular approach, mainly because of the NULL safety in Kotlin.
In order not to change the previous behavior, there is now a KeyGenerationStrategy with which you can change the behavior:

val repository = RepositoryFactoryBuilder
    .builder()
    .generateKeysUsing(UUIDObjectTypeKeyGenerator::class.java, KeyGenerationStrategy.ALL_UNMANAGED)
    .mock(MyRepository::class.java)

An entity that is not yet contained in the DataStore is seen as "unmanaged".


Besides, the mock is not really complete.
When an "unmanaged" entity is saved, Hibernate usually creates a clone.
This is therefore useful in order to prevent side effects from object manipulation.
The mock does not do that, which for example leads to the following code not working (in JPA + Hibernate, however, it does):

class Controller {
  fun userDetails(id: UUID): User {
    val user = repository.findByIdOrNull(id)
    user.eraseCredentials() // Manipulation of the object also manipulates the DataStore
    return user
  }
}

However, a (serialized) clone should perhaps be saved in the DataStore in order to prevent manipulation in the DataStore?

@coveralls
Copy link

coveralls commented Apr 18, 2021

Coverage Status

Coverage decreased (-0.2%) to 98.698% when pulling 5ae838e on tristanlins:feature-key-generation-unmanaged-entities into e854772 on mmnaseri:development.

Copy link
Owner

@mmnaseri mmnaseri left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for your PR! This is great code. A few very minor comments left for you. Also, would you mind running your code through google-java-format? If you don't have it installed, that's alright, I can do it when merging to master. If you can, it would also be great to have this change explained in either the README (same PR) or the gh-pages (separate PR)

@tristanlins tristanlins force-pushed the feature-key-generation-unmanaged-entities branch from a97f9cb to 5ae838e Compare May 22, 2021 06:47
@tristanlins
Copy link
Author

The desired changes have been made. 👋
See #187 for documentation update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants