Hibernate + Mysql Using Enums

Here in this article, I am going to explain how to match/map Enum in Hibernate with MySQL data type.
Enum can be mapped to a TINYINT but there is a catch here. First, let us see how we can map Enum to TINYINT.

First Define Enum

	public enum Status {
		private String name;

		Status(String name) {
			this.name = name;

		public String getName() {
			return this.name;

Define Enum type in hibernate entity

	@Column(columnDefinition = "tinyint")
	private Status status;

This will map to the status column with data type TINYINT. In some scenarios, you have just two values in enum. For example

	public enum Status {

Again, you can define the enum like above. But if you have column definition TINYINT(1) you are in trouble. Hibernate will through error that it cannot convert from boolean to String or in some cases it will not throw an error but load the null values in the loaded object.

So, what is this behavior? In MYSQL TINYINT range is -128 to 127 and bool or Boolean are just aliases to TINYINT(1). In MYSQL TINYINT is just 1 Byte TINYINT(1) is also the same but (1) here gives java jdbc driver hint that this is boolean and all non zero values transformed to true and zero converted to false.

Solution: if you want to use enum, in this case, you can change the data type to TINYINT(2).


Please share this post:
Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 11

3 thoughts on “Hibernate + Mysql Using Enums

  1. I’ve been browsing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my view, if all webmasters and bloggers made good content as you did, the net will be a lot more useful than ever before.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: