Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a FunctionalJava Option<Type> with Hibernate

I have a hibernate-mapped Java object, JKL, which is full of a bunch of normal hibernate-mappable fields (like strings and integers).

I'm added a new embedded field to it (which lives in the same table -- not a mapping), asdf, which is a fj.data.Option<ASDF>. I've made it an option to make it clear that this field may not actually contain anything (as opposed to having to handle null every time I access it).

How do I set up the mapping in my JKL.hbm.xml file? I'd like hibernate to automatically convert a null in the database to a none of fj.data.Option<ASDF> when it retrieves the object. It should also convert a non-null instance of ASDF to a some of fj.data.Option<ASDF>. Is there any other trickery that I have to do? Thank you.

like image 303
Mike Cialowicz Avatar asked May 15 '12 16:05

Mike Cialowicz


People also ask

What hibernate mapping types?

These types are “clob”, “blob”, “binary”, “text” etc. Clob and blob data types are present to maintain the data type mapping of large objects like images and videos.

Does hibernate allow multiple class mapping in one mapping file?

The hibernate-mapping element allows you to nest several persistent <class> mappings, as shown above. It is, however, good practice (and expected by some tools) to map only a single persistent class, or a single class hierarchy, in one mapping file and name it after the persistent superclass.

What is or mapping give an example of hibernate XML mapping file?

The mapping document is an XML document having <hibernate-mapping> as the root element, which contains all the <class> elements. The <class> elements are used to define specific mappings from a Java classes to the database tables.


2 Answers

I would suggest introducing FunctionalJava's Option in the accessors (getter and setter), while leaving Hibernate to handle a simple java field which is allowed to be null.

For example, for an optional Integer field:

// SQL
CREATE TABLE `JKL` (
    `JKL_ID` INTEGER PRIMARY KEY,
    `MY_FIELD` INTEGER DEFAULT NULL
)

You can map a Hibernate private field directly:

// Java
@Column(nullable = true)
private Integer myField;

You could then introduce Option at the accessor boundary:

// Java
public fj.data.Option<Integer> getMyField() {
    return fj.data.Option.fromNull(myField);
}

public void setMyField(fj.data.Option<Integer> value) {
    myField = value.toNull();
}

Does that work for your needs?

like image 191
ms-tg Avatar answered Nov 14 '22 23:11

ms-tg


You can use Hibernate's custom mapping types. Documentation is here. Here is an analogous example of mapping Scala's Option to a Hibernate mapping.

Simply put, you would need to extend the org.hibernate.UserType interface. You could also create a generic-typed base class with a JKL-typed sub-type, similar to what you see in the Scala example.

like image 28
jkl Avatar answered Nov 15 '22 01:11

jkl