Issue
Im trying to use UUID's as ids for my database but I simply do not get it working.
First attempt was:
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "uuid", strategy = "uuid4")
private UUID id;
but this is generating some ugly byte code. So I added a type annotation:
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "uuid", strategy = "uuid4")
@Type(type="org.hibernate.type.UUIDCharType")
private UUID id;
with this I get a character representation in my mysql database but querying the database using my repository:
public interface CommentsRepository extends CrudRepository<Comment, UUID> {
Comment findById(final UUID imageId);
}
wont find any result - even if an entry with the given UUID exists it wont return the result. Even if I use plain SQL directly on my database it wont find any result.
Is there something else I need to do to get UUID's working?
EDIT
Trying this:
@Data
@Entity
public class Comment implements Serializable {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Type(type = "uuid-char")
private UUID id;
}
and adding some default values:
@Component
@Slf4j
public class CommentsSampleData implements CommandLineRunner {
private final CommentsRepository repository;
@Autowired
public CommentsSampleData(final CommentsRepository repository) {
this.repository = repository;
}
@Override
public void run(String... args) {
repository.save(new Comment());
repository.save(new Comment());
repository.save(new Comment());
repository.save(new Comment());
}
}
Results in the following table:
performing:
SELECT * FROM comment WHERE id = 'b076a9f7-7e9e-4f5a-91f8-e66c7d076fac'
results in:
which means no result but there should be one. Using jpa also does not return anything.
Solution
Have you tried this uuid annotation maybe:
@Id
GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
private UUID id;
This sample should work with java.util.UUID
.
EDIT: I've read that you could run into problems with having a binary type set, so you could also try with explicitly setting it to a char
uuid with:
@Type(type="uuid-char")
Answered By - dreyus95