Last active
April 10, 2022 12:43
-
-
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
This file contains 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
@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 | |
} |
This file contains 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
@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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can find more details and integration tests with Micronaut in this repository