📜 ⬆️ ⬇️

Custom Types in Hibernate

Hibernate is a great ORM tool that can be customized to fit almost any need. In this topic, I will show how you can store fields of arbitrary type. For example, let's take an array of strings (String []) and a POJO object that we want to store in the database:
  1. public class StringArrayContainer { private Integer id ; private String [ ] tags ; // . }
  2. public class StringArrayContainer { private Integer id ; private String [ ] tags ; // . }
  3. public class StringArrayContainer { private Integer id ; private String [ ] tags ; // . }
  4. public class StringArrayContainer { private Integer id ; private String [ ] tags ; // . }
  5. public class StringArrayContainer { private Integer id ; private String [ ] tags ; // . }

In order for a Hibernate to save a field of type “array of strings” to the database, it is necessary (and sufficient) to write a class that implements the UserType interface and also refer to it in the mapping (hbm.xml file).
  1. public class StringArrayCustomType implements UserType {
  2. // TODO: write the implementation.
  3. }


Let us write the implementation of the class StringArrayCustomType method after method.


Finally, update the mapping file (hbm.xml):
  1. <class name = "StringArrayContainer" table = "containers" >
  2. <id name = "id" >
  3. <generator class = "native" />
  4. </ id >
  5. <property name = "tags" column = "tags" type = "StringArrayCustomType" />
  6. </ class >


And enjoy storing an array of strings.
')
PS In the next article we will fix a special criterion for filtering by this field.
______________________
The text was prepared in the Blog Editor from © SoftCoder.ru

Source: https://habr.com/ru/post/91328/


All Articles