Table of contents
  1. Accessing
  2. Collections
    1. Mapping to database examples
      1. Mapping Annotations
      2. map to blob
      3. use collection table
        1. with join
        2. with more hibernate annotations
        3. with mapkeycolumn
          1. field access
          2. property access
      4. use json type class
      5. use hibernate types to map as blob and serializable
      6. save as string , map to map
      7. use custom map
  3. Type Comparison




Accessing

  • If you use field-based access, your JPA implementation uses reflection to read or write your entity attributes directly.
    It also expects
    that you place your mapping annotations on your entity attributes.

  • If you use property-based access, you need to annotate the getter methods of your entity attributes with the required mapping annotations.
    Your JPA implementation then calls the getter and setter methods to access your entity attributes.

Collections

The persistent collections injected by Hibernate behave like ArrayList, HashSet, TreeSet, HashMap or TreeMap, depending on the interface
type.

  • java.util.List
  • java.util.Set
  • java.util.SortedSet
  • java.util.Map
  • java.util.SortedMap
  • java.util.Collection

Mapping to database examples

Mapping Annotations

types that I have used for mapping json or hashmap to mysql db

  • VARCHAR(16384)

    must have a max length to survive MariaDB DDL parser + hibernate validator

  • LONGTEXT

  • json

  • longvarchar

  • tinyblob

  • longblob

map to blob

public class MapBlob {
    @ElementCollection
    @Column(columnDefinition = "BLOB NOT NULL")
    @MapKeyColumn(columnDefinition = "BLOB NOT NULL")
    private final Map<String, String> userFiles = new HashMap<>();
}

use collection table

with join

public class MapBlob {
    @ElementCollection
    @MapKeyColumn(name = "key")
    @Column(name = "value")
    @CollectionTable(name = "preference", joinColumns = @JoinColumn(name = "user_id"))
    private Map<String, String> preferences;
}

with more hibernate annotations

public class MapBlob {
    @CollectionOfElements(targetElement = java.lang.String.class)
    @JoinTable(name = "BOOK_CHAPTER", joinColumns = @JoinColumn(name = "BOOK_ID"))
    @MapKey(columns = @Column(name = "CHAPTER_KEY"))
    @Column(name = "CHAPTER")
    private Map<String, String> chapters;

}

with mapkeycolumn

field access
public class MapBlob {
    @ElementCollection(targetClass = String.class)
    @CollectionTable(name = "MAP")
    @MapKeyColumn(name = "key")
    @Column(name = "value")
    private Map<String, String> map;
}
property access
public class MapBlob {
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "TABLENAME")
    @MapKeyColumn(name = "KEY")
    @Column(name = "VALUE")
    public Map<String, String> getMap() {
        return _map;
    }
}

use json type class

in build.gradle

implementation("com.vladmihalcea:hibernate-types-52:2.21.1")

@TypeDefs({
        @org.hibernate.annotations.TypeDef(name = "JSON", typeClass = JsonBlobType.class),
        @org.hibernate.annotations.TypeDef(name = "JSONB", typeClass = JsonBinaryType.class)
})
public class Entity {
    @Type(type = "json")
    @Column(columnDefinition = "jsonb")
    private String preferences;
}

use hibernate types to map as blob and serializable

public class MapBlob {
    @org.hibernate.annotations.Type(
            type = "org.hibernate.type.SerializableToBlobType",
            parameters = {@Parameter(name = "classname", value = "java.util.HashMap")}
    )
    public Map<String, SentimentFrequencyCounts> getModelData() {
        return modelData;
    }
}
public class MapBlob {
    @org.hibernate.annotations.Type(type = "org.hibernate.type.SerializableType")
    public Map<String, SentimentFrequencyCounts> getModelData() {
        return modelData;
    }
}

save as string , map to map

public class User extends AbstractEntity {
    @JsonIgnore //This variable is going to be ignored whenever you send data to a client(ie. web browser)
    private String preferences;

    @Transient //This property is going to be ignored whenever you send data to the database
    @JsonProperty("preferences") //Whenever this property is serialized to the client, it is going to be named "perferences" instead "preferencesObj"
    private Preferences preferencesObj;

    public String getPreferences() {
        return new ObjectMapper().writeValueAsString(preferencesObj);
    }

    public void setPreferences(String preferences) {
        this.preferences   = preferences;
        this.preferncesObj = new ObjectMapper().readValue(preferences, Preferences.class);
    }

    public Prefrences getPreferencesObj() {
        return preferencesObj;
    }

    public void setPreferencesObj(Preferences preferencesObj) {
        this.preferencesObj = preferencesObj;
    }
}

use custom map

public class Location implements Serializable {

    private String country;

    private String city;

    //Getters and setters omitted for brevity

    @Override
    public String toString() {
        return "Location{" +
                "country='" + country + ' ' +
                ", city='" + city + ' ' +
                '}';
    }
}

Type Comparison

Hibernate TypeDatabase TypeJDBC TypeType Registry
org.hibernate.type.StringTypestringVARCHARstring, java.lang.String
org.hibernate.type.MaterializedClobstringCLOBmaterialized_clob
org.hibernate.type.TextTypestringLONGVARCHARtext
org.hibernate.type.CharacterTypechar, java.lang.CharacterCHARchar, java.lang.Character
org.hibernate.type.BooleanTypebooleanBITboolean, java.lang.Boolean
org.hibernate.type.NumericBooleanTypebooleanINTEGER, 0 is false, 1 is truenumeric_boolean
org.hibernate.type.YesNoTypebooleanCHAR, ‘N’/’n’ is false, ‘Y’/’y’ is true. The uppercase value is written to the database.yes_no
org.hibernate.type.TrueFalseTypebooleanCHAR, ‘F’/’f’ is false, ‘T’/’t’ is true. The uppercase value is written to the database.true_false
org.hibernate.type.ByteTypebyte, java.lang.ByteTINYINTbyte, java.lang.Byte
org.hibernate.type.ShortTypeshort, java.lang.ShortSMALLINTshort, java.lang.Short
org.hibernate.type.IntegerTypesint, java.lang.IntegerINTEGERint, java.lang.Integer
org.hibernate.type.LongTypelong, java.lang.LongBIGINTlong, java.lang.Long
org.hibernate.type.FloatTypefloat, java.lang.FloatFLOATfloat, java.lang.Float
org.hibernate.type.DoubleTypedouble, java.lang.DoubleDOUBLEdouble, java.lang.Double
org.hibernate.type.BigIntegerTypejava.math.BigIntegerNUMERICbig_integer
org.hibernate.type.BigDecimalTypejava.math.BigDecimalNUMERICbig_decimal, java.math.bigDecimal
org.hibernate.type.TimestampTypejava.sql.TimestampTIMESTAMPtimestamp, java.sql.Timestamp
org.hibernate.type.TimeTypejava.sql.TimeTIMEtime, java.sql.Time
org.hibernate.type.DateTypejava.sql.DateDATEdate, java.sql.Date
org.hibernate.type.CalendarTypejava.util.CalendarTIMESTAMPcalendar, java.util.Calendar
org.hibernate.type.CalendarDateTypejava.util.CalendarDATEcalendar_date
org.hibernate.type.CurrencyTypejava.util.CurrencyVARCHARcurrency, java.util.Currency
org.hibernate.type.LocaleTypejava.util.LocaleVARCHARlocale, java.utility.locale
org.hibernate.type.TimeZoneTypejava.util.TimeZoneVARCHAR (Using the TimeZone ID)timezone, java.util.TimeZone
org.hibernate.type.UrlTypejava.net.URLVARCHARurl, java.net.URL
org.hibernate.type.ClassTypejava.lang.ClassVARCHAR (Using the class name)class, java.lang.Class
org.hibernate.type.BlobTypejava.sql.BlobBLOBblog, java.sql.Blob
org.hibernate.type.ClobTypejava.sql.ClobCLOBclob, java.sql.Clob
org.hibernate.type.BinaryTypeprimitive byte[]VARBINARYbinary, byte[]
org.hibernate.type.MaterializedBlobTypeprimitive byte[]BLOBmaterized_blob
org.hibernate.type.ImageTypeprimitive byte[]LONGVARBINARYimage
org.hibernate.type.BinaryTypejava.lang.Byte[]VARBINARYwrapper-binary
org.hibernate.type.CharArrayTypechar[]VARCHARcharacters, char[]
org.hibernate.type.CharacterArrayTypejava.lang.Character[]VARCHARwrapper-characters, Character[], java.lang.Character[]
org.hibernate.type.UUIDBinaryTypejava.util.UUIDBINARYuuid-binary, java.util.UUID
org.hibernate.type.UUIDCharTypejava.util.UUIDCHAR, VARCHARuuid-char
org.hibernate.type.PostgresUUIDTypejava.util.UUIDPostgreSQL UUIDpg-uuid
org.hibernate.type.SerializableTypeImplementors of java.lang.SerializableVARBINARYUnlike the other value types, multiple instances of this type are registered. It is registered once under java.io.Serializable and registered under the specific java.io.Serializable implementation class names