Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active April 10, 2022 12:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rponte/c9a8ad9aa629d0672a97f78d5b53afa0 to your computer and use it in GitHub Desktop.
Save rponte/c9a8ad9aa629d0672a97f78d5b53afa0 to your computer and use it in GitHub Desktop.
JPA and Hibernate: best way to mapping a primary key as UUID in MySQL 8.x
@Entity
class Proposal(
val name: String,
//
@Column(columnDefinition = "binary(16)") // this works but uses a MySQL's specific type
val customerId: UUID
) {
@Id
@GeneratedValue
/**
* By default Hibernate creates a column as BINARY(255) that works on INSERT but fails on SELECT
* In fact, BINARY(16) works like a CHAR on MySQL:
* - https://dev.mysql.com/doc/refman/8.0/en/binary-varbinary.html
*/
@Column(length = 16) // that works too and it's more compatible with other databases
val id: UUID? = null
}
@MicronautTest
class ProposalRepositoryTest(private val repository: ProposalRepository) {
@Test
fun `should find by id`() {
// scenario
val proposal = repository.save(Proposal(
name = "p1",
customerId = UUID.randomUUID()
))
// action
val found = repository.findById(proposal.id)
// validation
with(found) {
assertTrue(isPresent)
assertEquals(proposal.id, get().id)
assertEquals(proposal.customerId, get().customerId)
}
}
@Test
fun `should find by id and customer id`() {
// scenario
val proposal = repository.save(Proposal(
name = "p2",
customerId = UUID.randomUUID()
))
// action
val found = repository.findByIdAndCustomerId(
id = proposal.id!!,
customerId = proposal.customerId
)
// validation
with(found) {
assertTrue(isPresent)
assertEquals(proposal.id, get().id)
assertEquals(proposal.customerId, get().customerId)
}
}
}
@rponte
Copy link
Author

rponte commented Jul 8, 2021

You can find more details and integration tests with Micronaut in this repository

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