Skip to main content

Posts

Showing posts with the label Enumeration

Java : How to make enums inside java class

How to make enums inside java class You can use enums inside a class as shown in the code below. User.Gender.MALE or FEMALE  is always associated with the user property. However if you need Gender to be generic and u want to use it with animals also, then you might want to keep this enum in a separate class. package com.ekiras.demo; public class User { public enum Gender{ MALE, FEMALE } private String name; private String address; private String email; private String password; private Gender gender = Gender.MALE; } You can also use the enums with parameters inside class as shown below. package com.ekiras.demo; public class User { public enum Gender{ MALE("male"), FEMALE("female"); String value; Gender(String value){ this.value=value; } } private String name; private String address; private String email; private String password; private Gender gender = Gender.MALE; }

How to use Enums in Hibernate Persistence

Points To Remember Enums are special java classes that are used to declare constants and methods. Enums have all the variables declared as public static final. Enums variables can be compared using ==  operator. End of a enum can be declared by a semi colon, but this is optional. There are two ways to use Enums  ORDINAL (saves the enum values in integer format starting from 0.) STRING (saves the enum value in String, takes the value of the field itself. ) Use Enums in Hibernate In this example we will be using Enums to save a value in database using hibernate. Suppose we have a Enum named Level  and we want to save it in database using hibernate persistence.Then we can map this in the following way. Level.java This is an Enum that defines the level of difficulty of a question. package com.ekiras.enums; public enum Level { LEVEL_ONE, LEVEL_TWO, LEVEL_THREE, LEVEL_FOUR, LEVEL_FIVE; } Qusetion.java This class contains the enum as a field that will be saved to the databa...