theChoosyBeggar
theChoosyBeggar

Reputation: 332

Cannot retrieve data using java.util.UUID from Mysql db where primary key is binary(128)

Like the title says. I am storing entities in a MySql DB using JPA and Hibernate. I am using a java.util.UUID on the java side as my @Id. On the DB side the primary key is a binary(128). Persisting works fine. No errors. But retrieving the data using the UUID as the key returns null every time. Looking in the database the hex used as the binary appears to match the java.lang.String representation of the UUID so everything seems to be getting translated smoothly. But like I said tests fail to confirm retrieval when retrieval is attempted. Switching to another datatype for my @Id isn't really an option because I need to know the id even before persistence and UUID is the best way to get a unique id without having to know the state of the DB. Here are my entity classes, the test that fails, and my schema definition.

schema def:

create table PLAYER(
ID binary(128) PRIMARY KEY NOT NULL,
USERNAME VARCHAR(50) unique NOT NULL,
PASSWORD varchar(100) NOT NULL,
JOIN_DATE DATETIME);

Player.java

@Entity
@Table(name = "PLAYER")
public class Player extends AbstractEntity{

@Column(name = "USERNAME")
private String username;

@Column(name = "PASSWORD")
private String password;


@Column(name = "JOIN_DATE")
private LocalDate joinDate;

AbstractEntity.java

@MappedSuperclass
public abstract class AbstractEntity implements Serializable {

@Id
@Column(name = "ID")
protected UUID id;

Finally, the test that fails

    @Test
    void findById() {

    Player patrick = new Player();
    patrick.setId(uuid);
    patrick.setUsername("patrick");
    patrick.setPassword("password");
    patrick.setJoinDate(LocalDate.now());
    playerRepo.save(patrick);

    Optional<Player> result = playerRepo.findById(uuid);
    if (result.isEmpty()) {
        fail();
    }
    }

Upvotes: 0

Views: 840

Answers (2)

SternK
SternK

Reputation: 13041

Try to correct your test case in the following way:

@Test
void findById() {

   Player patrick = new Player();
   // ...
   playerRepo.save(patrick);
   entityManager.flush();

   Optional<Player> result = playerRepo.findById(uuid);
   // ...
}

Upvotes: 0

Janardhan
Janardhan

Reputation: 89

you can add the columnDefinition property to Column annotation

@Column(name = "ID", columnDefinition="BINARY(128)")
protected UUID id;

Upvotes: 1

Related Questions